輸入一行單詞序列,相鄰單詞之間由1個或多個空格間隔,請對應地計算各個單詞的長度。
注意,若是有標點符號(如連字符,逗號),標點符號算做與之相連的詞的一部分。沒有被空格間開的符號串,都算做單詞。ios
She was born in 1990-01-02 and from Beijing city.
3,3,4,2,10,3,4,7,5
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 int main() 5 { 6 char s[1001]; 7 int t = 0, a[1001] = { 0 }, m = 0; 8 gets(s); 9 int l=strlen(s); 10 for (int i = 0; i <=l ; ++i) 11 { 12 if (s[i] != ' '&&s[i] != '\0') 13 { 14 t++; 15 } 16 else if (s[i - 1] != ' '&&(s[i] == ' '||s[i] == '\0')) 17 { 18 a[m] = t; 19 ++m; 20 } 21 if (s[i] == ' '&&s[i + 1] != ' ') 22 { 23 t = 0; 24 } 25 } 26 int j = 0; 27 cout << a[0]; 28 while (a[j+1] != 0) 29 { 30 ++j; 31 cout << "," << a[j]; 32 } 33 return 0; 34 }
//注意vs是不支持gets的,其用的是gets_s,但oj上又不支持gets_s;數組
另解spa
1 #include <string> 2 #include <iostream> 3 using namespace std; 4 5 const int N = 310; 6 string s[N]; // 存儲字符串的每一個單詞 7 8 int main() { 9 string str; 10 getline(cin, str); // 不要用cin,由於有空格 11 int len = 0; // 數組下標 12 for (int i = 0; i < str.size(); i++) { 13 if (str[i] != ' ') { // 若當前字符不是空格 14 s[len] += str[i]; 15 } 16 else if (str[i + 1] != ' ') { // 若當前字符是空格且當前字符的後面一個字符不是空格 17 len++; // 數組下標加一 18 } 19 } 20 for (int i = 0; i <= len; i++) { 21 cout << s[i].size(); 22 if (i < len) cout << ","; // 英文逗號 23 } 24 25 return 0; 26 }