简体   繁体   中英

Splitting a string and adding to list using Regex and C#

I have a string where the number of words might vary. Like:

string a_string = " one two three four five six seven etc etc etc "; 

How do I split the string into 5 words each, and each of those are added it to a list, such that it becomes a list of string (with each string containing 5 words). I think list would be better because number of words in string can vary, so list can grow or shrink accordingly.

I tried using Regex to get first 5 words through below line of code:

Regex.Match(rawMessage, @"(\\w+\\s+){5}").ToString().Trim();

but bit unsure on how to proceed further and add to list dynamically and robustly. I guess Regex can further help, or some awesome string/list function? Can you please guide me a bit?

Eventually, I would want list[0] to contain "one two three four five" and list[1] to contain "six seven etc etc etc", and so on.. Thanks.

var listOfWords = Regex.Matches(a_string, @"(\w+\s+){1,5}")
     .Cast<Match>()
     .Select(i => i.Value.Trim())
     .ToList();

Splitting for words does not require regex, string provides this capability:

var list = str.Split(' ').ToList();

ToList() is a LINQ extension method for converting IEnumerable<T> objects to lists ( Split() method returns an array of strings).

To group a list by 5 words, use this code snippet:

var res = list
    .Select((s, i) => new { Str = s, Index = i })
    .GroupBy(p => p.Index/5)
    .Select(g => string.Join(" ", g.Select(v => v.Str)));

You can use simple

a_string.Split(' ');

And then loop throught resulting array and fill your list as you want, for example

int numOfWords = 0;
int currentPosition = 0;
foreach (var str in a_string.Split(' '))
{
   if (numOfWords == 5)
   {
     numOfWords = 0;
     currentPosition++;
   }
   list[currentPosition] += str;
   numOfWords++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM