将字符串拆分为单词数组

Oma*_*mar 2 c# arrays string

我想在string不使用的情况下将a 分成一个单词数组string.Split.我已经尝试过这段代码了,但它无法将结果分配给数组

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 = "";
}
Run Code Online (Sandbox Code Playgroud)

Ian*_*Ian 5

你需要一种index pointer将你的物品一个一个地放到数组中:

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
Run Code Online (Sandbox Code Playgroud)

在我的示例中,索引指针已命名 currentWordNo