Reputation: 289
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.
Upvotes: 2
Views: 2214
Reputation: 1332
var listOfWords = Regex.Matches(a_string, @"(\w+\s+){1,5}")
.Cast<Match>()
.Select(i => i.Value.Trim())
.ToList();
Upvotes: 4
Reputation: 726639
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)));
Upvotes: 1
Reputation: 10376
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++;
}
Upvotes: 0