2016年
1、输入一行文本,求文本中的每个单词的长度。
以 word length
this 4
的格式输出
下面给出代码:
方法一
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string s;
getline(cin,s);
string word;
cout << setw(6) << "word" << setw(8) << "length" << endl;
while (!s.empty()) {
if (s.find(" ") == s.npos) {
word = s.substr(0);
cout << setw(6) << word << setw(8) << word.length() << endl;
break;
}
word = s.substr(0,s.find(" "));
cout << setw(6) << word << setw(8) << word.length() << endl;
s.erase(0,s.find(" ") + 1);
}
return 0;
}
测试结果:
方法二
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string s;
getline(cin,s);
string word;
size_t lastPos = 0;
cout << setw(6) << "word" << setw(8) << "length" << endl;
do {
word = s.substr(lastPos,s.find(" ",lastPos) - lastPos);
cout << setw(6) << word << setw(8) << word.length() << endl;
lastPos = s.find(" ",lastPos);
} while (lastPos++ != s.npos);
return 0;
}
这里我想说下关于提取字串的函数substr:
string substr (size_t pos = 0, size_t len = npos) const;
第一个参数是起始下标,第二个参数是想要提取的字符串数(当len的值大于剩余字符串的大小时,就提取尽可能多的字符)。
详见官方文档:http://www.cplusplus.com/reference/string/string/substr/
方法三(最简洁)
当然也可以用 strtok() 和 strlen() :
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
using namespace std;
int main(){
char s[20];
gets(s);
char *word = strtok(s," ");
while (word) {
cout << word << " " << strlen(word) <<endl;
word = strtok(NULL, " ");
}
return 0;
}
注意会报warning: this program uses gets(), which is unsafe.