Reputation: 73
I want to split a string into multiple strings based on the following criteria:
For example: "hello how are you" I want to split into:
Can't repeat multiple times.
What I got so far is this:
string input = "hello how are you";
List<string> words = input.Split(' ').ToList();
List<string> inputs = new List<string>();
string temp = String.Empty;
for (int i = 0; i < words.Count; i++)
{
temp += words[i] + " ";
if (i > 0)
{
inputs.Add(temp);
}
}
It outputs the following:
hello how
hello how are
hello how are you
I want to get the others too and need a little help with that.
Upvotes: 3
Views: 201
Reputation: 4903
One approach would be to iterate over each word and get all its possible sequences.
Example:
string input = "hello how are you";
List<string> words = input.Split(' ').ToList();
List<string> inputs = new List<string>();
for (int i = 0; i < words.Count; i++)
{
var temp = words[i];
for(int j = i+1;j < words.Count;j++) {
temp += " " + words[j];
inputs.Add(temp);
}
}
//hello how
//hello how are
//hello how are you
//how are
//how are you
//are you
Upvotes: 5
Reputation: 31
Here's the pseudocode
for (int i = 0; i < words.Count - 1; i++)
{
for each (int j = i + 1; j < words.Count; j++)
{
//rebuild string from words[i] through words[j] and add to list
}
}
The idea is to consider each word except the last as a starting word (since it can't have a words following it). For starting word, consider each possible ending word (the first would be the next word in the list and the last would be the last word). Then for each starting/ending word pair, rebuild the string out of all the words in between, and add it to the list
Upvotes: 2