c# 根据空格分割字符串

在C#中,可以使用以下方法根据多个空格来分割字符串:

使用 Split() 方法:


string input = "  Hello   World   How   are   you?  ";
string[] words = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

// words 数组包含: ["Hello", "World", "How", "are", "you?"]

使用正则表达式:

using System.Text.RegularExpressions;

string input = "  Hello   World   How   are   you?  ";
string[] words = Regex.Split(input, @"\s+");

// words 数组包含: ["", "Hello", "World", "How", "are", "you?", ""]

需要注意的是,使用正则表达式分割字符串时,结果数组可能会包含空字符串,因为正则表达式可能会匹配到连续的空白字符。如果需要移除这些空字符串,可以使用 Array.Where() 方法或 StringSplitOptions.RemoveEmptyEntries 选项。

使用 LINQ:

string input = "  Hello   World   How   are   you?  ";
string[] words = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
words = words.Where(w => !string.IsNullOrWhiteSpace(w)).ToArray();

// words 数组包含: ["Hello", "World", "How", "are", "you?"]

相关推荐

  1. c# 根据空格分割字符串

    2024-06-17 22:44:02       8 阅读
  2. Linux c根据分隔符解析字符串

    2024-06-17 22:44:02       4 阅读
  3. C++ 字符串分割

    2024-06-17 22:44:02       7 阅读
  4. c语言-输入包含空格字符串

    2024-06-17 22:44:02       17 阅读
  5. C++字符去除空格反转顺序输出

    2024-06-17 22:44:02       35 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-17 22:44:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-17 22:44:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-17 22:44:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-17 22:44:02       18 阅读

热门阅读

  1. 中介子方程二十二

    2024-06-17 22:44:02       4 阅读
  2. 什么是props?

    2024-06-17 22:44:02       5 阅读
  3. 计算机网络期末复习

    2024-06-17 22:44:02       6 阅读
  4. mysql如何创建并执行事件?

    2024-06-17 22:44:02       5 阅读
  5. C# —— 枚举

    2024-06-17 22:44:02       8 阅读
  6. 工具清单 - 看板工具

    2024-06-17 22:44:02       8 阅读
  7. 基于深度学习的向量图预测

    2024-06-17 22:44:02       8 阅读
  8. CSRF令牌解析:保护web应用免受攻击

    2024-06-17 22:44:02       5 阅读
  9. 驱动面试题

    2024-06-17 22:44:02       5 阅读
  10. 【AI应用探讨】— 文心一言模型应用场景

    2024-06-17 22:44:02       6 阅读
  11. 【C语言实现内核链表】

    2024-06-17 22:44:02       7 阅读