如何在其中第三空间中分开字符串

  • 本文关键字:字符串 空间 在其中 c#
  • 更新时间 :
  • 英文 :


我必须在c#中的每一个第三个出现空间中拆分一个字符串。然后从末端遇到的每3个空间向后拆分相同的字符串。

我尝试使用 IndexOf()Substring()这样的

string sub1 = q.Substring(q.IndexOf(q.Split(' ')[3]));

例如。字符串-Where can I find medicine for headache

预期输出 -

  1. 3个子字符串为-Where can Ifind medicine forheadache
  2. 3个子字符串为-Wherecan I findmedicine for headache

正向外壳相当简单。由一个空间拆分,因此您在一个数组中具有所有元素,然后根据需要SkipTake分开:

public static IEnumerable<string> SplitForward(string input, char c, int n)
{
    var items = input.Split(c);
    var x = 0;
    while(x<items.Length)
    {
        yield return String.Join(c.ToString(), items.Skip(x).Take(n));
        x += n;
    }
}

向后的情况有些复杂,您第一次Take可能不是完整的3个项目:

public static IEnumerable<string> SplitBackward(string input, char c, int n)
{
    var items = input.Split(c);
    var x = 0;
    var take = items.Length%n;
    while(x<items.Length)
    {
        if(take == 0) take = n;
        yield return String.Join(c.ToString(), items.Skip(x).Take(take));
        x += take;
        take = n;
    }
}

用法:

var input = "Where can I find medicine for headache";            
var forwards = SplitForward(input, ' ',3).ToArray();
var backwards = SplitBackward(input, ' ',3).ToArray(); 

实时示例:https://rextester.com/oluk79677

我敢肯定,这样做的方法更优雅,但是以下循环会生成您想要的输出。

    string text = "Where can I find medicine for headache"; 
    var splitText = text.Split(' ');
    var fromStart = "";
    var fromEnd = "";
    for(int i = 0; i< splitText.Length;i++){
        fromStart = fromStart + splitText[i];
        fromEnd = fromEnd + splitText[i];
        if((i+1) % 3 == 0 && i != splitText.Length - 1)
            fromStart = fromStart + ", ";
        else
            fromStart = fromStart + " ";
        if(i % 3 == 0 && i != splitText.Length - 1)
            fromEnd = fromEnd + ", ";
        else
            fromEnd = fromEnd + " ";
    }
    Console.WriteLine(fromStart);
    Console.WriteLine(fromEnd);

最新更新