如何在出现第三个空格时拆分字符串?

时间:2019-05-22 10:47:09

标签: 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

2 个答案:

答案 0 :(得分:4)

向前的情况相当简单。按空格分隔,这样就可以将所有元素放在一个数组中,然后根据需要分别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可能不是全部三项:

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

答案 1 :(得分:0)

我敢肯定有很多更优雅的方法可以做到这一点,但是下面的for循环会生成您想要的输出。

    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);