NOIP 2018普及組複賽第1題.jpg
一、C程序
解法一:用gets()函數
#include <stdio.h> #include <string.h> int main() { // 將控制檯的數據重定向到文件裏 freopen("title.in", "r", stdin); freopen("title.out", "w", stdout); char s[100]; gets(s); int total = 0; printf("%d\n", sizeof(s)); // 這裏只能用strlen,不能用sizeof // 因爲sizeof(s)=sizeof(s)/sizeof(char)=100 for(int i = 0; i < strlen(s); i++) { if(s[i] != ' ') { total++; } } printf("%d", total); return 0; }
解法二:用scanf()函數
#include <stdio.h> #include <string.h> int main() { // 將控制檯的數據重定向到文件裏 freopen("title.in", "r", stdin); freopen("title.out", "w", stdout); char s[100]; // 不能使用scanf("%s",s);因爲遇到第一個空格就會結束 // 符號^表示取反,[^\n]表示除了換行符,其他的字符都可以讀取 scanf("%[^\n]", s); int total = 0; // 這裏只能用strlen,不能用sizeof // 因爲sizeof(s)=sizeof(s)/sizeof(char)=100 for(int i = 0; i < strlen(s); i++) { if(s[i] != ' ') { total++; } } printf("%d", total); return 0; }
二、C++程序
#include <iostream> #include <stdio.h> // freopen和stdin、stdout要用到此頭文件 using namespace std; int main() { // 將控制檯的數據重定向到文件裏 freopen("title.in", "r", stdin); freopen("title.out", "w", stdout); string s; getline(cin, s); int total = s.length(); // for循環裏面的s.length()不要寫成total,因爲total是不斷減小的 for(int i = 0; i < s.length(); i++) { if(s[i] == ' ') { total--; } } cout << total << endl; return 0; }
三、總結
本題考察的知識點有兩個: (1)輸入帶空格的字符串 常用的scanf和cin,遇到第一個空格就會停止輸入。 C語言可以使用gets()輸入帶空格的字符串。當然使用scanf(“%[^\n]”, s)也可以。 C++可以使用getline()輸入帶空格的字符串
(2)求字符串的長度 C語言的字符數組可以使用strlen(s); C++的string可以使用s.length()或s.size()。