Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split text value into array with words in C#?

Tags:

arrays

string

c#

Is it possible to save value of txtSearche in array splitted into seperate words?

txtSearche = "put returns between paragraphs";

something like this:

 StringBuilder sb = new StringBuilder(txtSearche);

array1 = sb[1]   = put
array2 = sb[2]   = returns
array3 = sb[3]
array4 = sb[4]
array5 = sb[5]

how to do it correct?

like image 269
r.r Avatar asked Sep 09 '10 11:09

r.r


3 Answers

Yes try this:

string[] words = txtSearche.Split(' ');

which will give you:

words[0]   = put
words[1]   = returns
words[2]   = between
words[3]   = paragraphs

EDIT: Also as Adkins mentions below, the words array will be created to whatever size is needed by the string that is provided. If you want the list to have a dynamic size I would say drop the array into a list using List wordList = words.ToList();

EDIT: Nakul to split by one space or more, just add them as parameters into the Split() method like below:

txtSearche.Split(new string[] { " ", "  ", "   " }, StringSplitOptions.None);

or you can tell it simply to split by a single space and ignore entries that are blank, caused by consecutive spaces, by using the StringSplitOptions.RemoveEmptyEntries enum like so

txtSearche.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
like image 177
Iain Ward Avatar answered Nov 03 '22 01:11

Iain Ward


You could use String.Split.

like image 23
Steven Sudit Avatar answered Nov 03 '22 00:11

Steven Sudit


Below example will split the string into an array with each word as an item...

string[] words = txtSearche.Split(' ');

You can find more details here

like image 24
Matt Avatar answered Nov 03 '22 00:11

Matt