C++中統計給定字串中的單詞數
給定一個包含單詞的句子或字串,單詞之間可能包含空格、換行符和製表符。任務是計算字串中單詞的總數並列印結果。
輸入 − 字串 str = “welcome to\n tutorials point\t”
輸出 − 字串中單詞的數量為 − 4
說明 − 字串中有四個單詞,即 welcome、to、tutorials、point,其餘是單詞之間的空格(“ ”)、換行符(\n)和製表符(\t)。
輸入 − 字串 str = “\nhonesty\t is the best policy”
輸出 − 字串中單詞的數量為 − 5
說明 − 字串中有五個單詞,即 honesty、is、the、best、policy,其餘是單詞之間的空格(“ ”)、換行符(\n)和製表符(\t)。
下面程式中使用的方法如下
這個問題有多種解法。所以讓我們首先看看我們在下面的程式碼中使用的更簡單的方案:
建立一個字元型別的陣列來儲存字串,例如,str[]
宣告兩個臨時變數,一個count用於計數字符串中單詞的數量,另一個temp用於執行標誌操作。
開始迴圈,當str不為空時
在迴圈內,檢查IF *str = 空格 OR *str = 換行符 OR *str = 製表符,則將temp設定為0
否則,如果temp = 0,則將temp設定為1並將count的值加1
將str指標加1
返回count中的值
列印結果
示例
#include using namespace std; //count words in a given string int total_words(char *str){ int count = 0; int temp = 0; while (*str){ if (*str == ' ' || *str == '\n' || *str == '\t'){ temp = 0; } else if(temp == 0){ temp = 1; count++; } ++str; } return count; } int main(){ char str[] = "welcome to\n tutorials point\t"; cout<<"Count of words in a string are: "<<total_words(str); return 0; }
輸出
如果執行上述程式碼,將生成以下輸出:
Count of words in a string are: 4
廣告