c# -在多个字符串中拆分带有空格的字符串

本文关键字:字符串 空格 拆分 | 更新日期: 2023-09-27 18:13:13

我有一个字符串,是一个句子。例如:

string sentence = "Example sentence";

如何将这个字符串分割成多个字符串?所以:

string one = "Example";
string two = "sentence";

c# -在多个字符串中拆分带有空格的字符串

这是一个骗局,但你正在寻找字符串。Split (https://msdn.microsoft.com/en-us/library/b873y76a(v=vs.110).aspx)——

public class Program
{
    public static void Main(string[] args)
    {
        string sentence = "Example sentence";
        string[] array = sentence.Split(' ');
        foreach (string val in array.Where(i => !string.IsNullOrEmpty(i)))
        {
            Console.WriteLine(val);
        }
    }
}

. where确保跳过空字符串

可以了

string sentence = "Example sentence";
string [] sentenses = sentence.Split(' ');
string one = sentenses[0];
string two = sentenses[1];