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?"]
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,可以使用string.Split()方法对字符串进行分割。该方法的使用形式为:string[] result = originalString.Split(separatorChars, StringSplitOptions);其中,separatorChars是一个字符数组,表示分隔符;StringSplitOptions是一个枚举类型,表示是否移除空白项。例如,以下代码将一个字符串按照逗号进行分隔: string originalString = "apple,banana,orange"; string[] result = originalString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in result) { Console.WriteLine(s); } // 输出: // apple // banana // orange 除了单个字符分隔符,还可以使用多个字符分隔符,例如以下代码将一个字符串按照逗号和空格两种分隔符进行分隔: string originalString = "apple, banana, orange"; string[] result = originalString.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in result) { Console.WriteLine(s); } // 输出: // apple // banana // orange 需要注意的是,如果分隔符是一个字符串而不是一个字符,可以使用String.Split()方法的重载形式,例如以下代码将一个字符串按照换行符进行分隔: string content = "line1\nline2\nline3"; string[] getAry = content.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in getAry) { Console.WriteLine(s); } // 输出: // line1 // line2 // line3 --相关问题--: 1. C#中还有哪些常用的字符串操作方法? 2. 如何在C#中将字符串转换为数字类型? 3. C#中如何判断一个字符串

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值