C# Split text to parts by spaces QUESTION

Hello,
I have a little problem in my script and i can’t find the solution. I have script and i want it to see what a text component contains e.g “I have a cat” and then i want to take that and split it to parts based on the spaces e.g “I” “have” “a” “cat”. I would also like to take those spited parts and set them in some strings.

Thank you in advance.

1 Like

Simplest solution without re-inventing the wheel would be the string.Split(…) method.

You can provide characters or char sequences (strings) which act as seperators, for instance space, and also decide whether to remove empty strings from the results. You’ll get the results in an array.

If you want to go for more advanced stuff, such as pattern and the like, you might be interested in regular expressions. (e.g. the namespace System.Text.RegularExpressions).

3 Likes

Thank you very much. I will appresiate if you could show me how it’s done in a small script si I can know how to inser it to my script.

Something like

char[] separators = new char[] { ' ', '.' };
string example = "This is an example.";

foreach(var word in example.Split(separators, StringSplitOptions.RemoveEmptyEntries))
{
    Debug.Log(word);
}

That should get you started.

2 Likes