簡體   English   中英

將字符串拆分為單詞數組

[英]Split string into array of words

我想在不使用string.Split情況下將string拆分為單詞數組。 我已經嘗試過這段代碼了,但它無法將結果分配給數組

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 = "";
}

你只需要一種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

在我的示例中,索引指針名為currentWordNo

嘗試使用正則表達式 ,如下所示:

  string str = "Hello, how are you?";

  // words == ["Hello", "how", "are", "you"] 
  string[] words = Regex.Matches(str, "\\w+")
    .OfType<Match>()
    .Select(m => m.Value)
    .ToArray();

String.Split不是一個好選擇,因為要分割的字符太多' ' (space), '.' ','';' '!' 等等

只是空間之間的東西,還有標點符號來考慮, 非中斷空格等看一看這樣的輸入:

  string str = "Bad(very bad) input to test. . ."

注意

  1. “壞”之后沒有空間
  2. 不間斷的空間
  3. 完全停止后的附加空間

而正確的輸出應該是

  ["Bad", "very", "bad", "input", "to", "test"] 

您還可以使用列表來創建單詞列表:

    string str = "Hello, how are you?";
    string tmp = "";
    List<string> ListOfWords = new List<string>();

    int j = 0;

    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

        ListOfWords.Add(tmp);
        tmp = "";
    }
    ListOfWords.Add(tmp);

通過這種方式,您可以避免計算單詞的數量,並且代碼更簡單。 使用ListOfWord [x]讀取任何單詞

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM