3

I want to split a string into multiple strings based on the following criteria:

  • It has to be minimum 2 words together
  • Each word must be next to each other

For example: "hello how are you" I want to split into:

  • "hello how are you"
  • "hello how are"
  • "hello how"
  • "how are"
  • "how are you"
  • "are you"

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.

0

2 Answers 2

5

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 
Sign up to request clarification or add additional context in comments.

2 Comments

You beat me to this!
That's what I was looking for exactly. Thanks for the help, appreciate it.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.