Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split by every 3 words

Tags:

string

c#

split

I've got a problem. I need to split my every string like this: For example: "Economic drive without restrictions"

I need array with sub string like that: "Economic drive without" "drive without restrictions"

For now i have this:

            List<string> myStrings = new List<string>();
        foreach(var text in INPUT_TEXT) //here is Economic drive without restrictions
        {
            myStrings.DefaultIfEmpty();
            var textSplitted = text.Split(new char[] { ' ' });
            int j = 0;
            foreach(var textSplit in textSplitted)
            {

                int i = 0 + j;
                string threeWords = "";
                while(i != 3 + j)
                {
                    if (i >= textSplitted.Count()) break;
                    threeWords = threeWords + " " + textSplitted[i];
                    i++;
                }
                myStrings.Add(threeWords);
                j++;
            }
        }
like image 817
sidron Avatar asked Jun 22 '26 01:06

sidron


1 Answers

You could use this LINQ query:

string text = "Economic drive without restrictions";
string[] words = text.Split();
List<string> myStrings = words
    .Where((word, index) => index + 3 <= words.Length)
    .Select((word, index) => String.Join(" ", words.Skip(index).Take(3)))
    .ToList();

Because others commented that it would be better to show a loop version since OP is learning this language, here is a version that uses no LINQ at all:

List<string> myStrings = new List<string>();
for (int index = 0; index + 3 <= words.Length; index++)
{ 
    string[] slice = new string[3];
    Array.Copy(words, index, slice, 0, 3);
    myStrings.Add(String.Join(" ", slice));
}
like image 145
Tim Schmelter Avatar answered Jun 23 '26 14:06

Tim Schmelter