Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into array of words

Tags:

arrays

string

c#

I want to split a string into an array of words without using string.Split. I tried already this code and it is working but cant assign the result into the array

string str = "Hello, how are you?";
string tmp = "";
int word_counter = 0;
for (int i = 0; i < str.Length; i++)
{
     if (str[i] == ' ')
     {
         word_counter++;
     }
}
string[] words = new string[word_counter+1];

for (int i = 0; i < str.Length; i++)
{
    if (str[i] != ' ')
    {
        tmp = tmp + str[i];
        continue;
    }
    // here is the problem, i cant assign every tmp in the array
    for (int j = 0; j < words.Length; j++)
    {
        words[j] = tmp;
    }
    tmp = "";
}
like image 777
Omar Avatar asked Jul 04 '26 22:07

Omar


1 Answers

You just need a kind of index pointer to put up your item one by one to the array:

string str = "Hello, how are you?";
string tmp = "";
int word_counter = 0;
for (int i = 0; i < str.Length; i++) {
    if (str[i] == ' ') {
        word_counter++;
    }
}
string[] words = new string[word_counter + 1];
int currentWordNo = 0; //at this index pointer
for (int i = 0; i < str.Length; i++) {
    if (str[i] != ' ') {
        tmp = tmp + str[i];
        continue;
    }
    words[currentWordNo++] = tmp; //change your loop to this
    tmp = "";
}
words[currentWordNo++] = tmp; //do this for the last assignment

In my example the index pointer is named currentWordNo

like image 125
Ian Avatar answered Jul 06 '26 12:07

Ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!