代码之家  ›  专栏  ›  技术社区  ›  Ahmad

确定一个字符串的中间空格,并将其拆分为两个字符串。净额

  •  1
  • Ahmad  · 技术社区  · 8 年前

    我有一个字符串,我将其拆分为两个字符串,如下所示:

    string a="Hello World here i am ";
    if(a.Length > 10)
    {
        string[] result = a.Split(' '); // Divides string into 2 where there is a Space this is type of array 
        string C = result[0]; // This takes the 1st value of that array 
        string D = result[1];);//This takes the  value of that array
        Console.WriteLine(C);
        Console.WriteLine(D);
    }
    

    这是一个控制台行测试实例,我需要2个字符串将注释放在注释框的2行中。

    所以这个字符串 a 可能是什么,问题是我只有两行。我想把它从这个字符串中间的空格中分离出来,例如,一个计算字符数的代码,如示例中所示 a.Length > 10 然后找到这个字符串中间的空格,在这个例子中是 Hello World here I am 在这里应该可以看到 Hello world 在一个字符串中,我在另一个字符串中。有什么帮助吗?我试着看了很多这样的例子:

    string s = "there is a cat";
    //
    // Split string on spaces.
    // ... This will separate all the words.
    //
    string[] words = s.Split(' ');
    foreach (string word in words)
    {
        Console.WriteLine(word);
    }
    

    这将它们分割成几行,并且不真正返回2个字符串,我只想要2个字符串。提前感谢

    1 回复  |  直到 8 年前
        1
  •  3
  •   Steve    8 年前

    我们可以通过一些IEnumerable扩展来实现,比如Take和Skip

    string a = "This is a long phrase to test the splitting around the middle space";
    string[] parts = a.Split(' ');
    string first = string.Join(" ", parts.Take(parts.Length / 2));
    string second = string.Join(" ", parts.Skip(parts.Length / 2));
    Console.WriteLine(first);
    Console.WriteLine(second);
    

    然而,这并不是最好的方法,因为这种方法不计算单词的长度,因此你可以以比另一行短得多的行结束。

    如果需要两个长度相同的字符串,那么可以使用这样的循环

    string a = "This is a long text to test the splitting around the middle length of the phrase";
    string[] parts = a.Split(' ');
    
    int counter = 0;
    string first = "";
    int middle = a.Length / 2;
    while (first.Length < middle)
    {
        first += parts[counter] + " ";
        counter++;
    }
    string second = string.Join(" ", parts.Skip(counter));
    Console.WriteLine(first);
    Console.WriteLine(second);