编写程序,读入几行文本,并打印一个表格,显示不同单词在文本中出现的次数。
strtok()
拆解句子#include<iostream>
#include<string>
#include<iomanip>
#pragma warning(disable:4996)
using namespace std;
const int MaxSize = 100;
//string到char指针需要手动转换,使用动态
int main() {
//string word[MaxSize];
string input = "to be or not to be , that is a question";
//cin >> input; //cin支持string嗷
//string到char的动态转换
int length = input.length();
char *str = new char[length + 1];
input.copy(str, length, 0);
//第一个参数是接受的指针,第二个参数是复制的长度,第三个参数是开始位置可以不加,默认是从指针头
str[length] = 0;
//拆解单词
char *p;
char *word[MaxSize] = { 0, };
p = strtok(str, " ");
for (int i = 0; p != NULL; i++) {
word[i] = p;
p = strtok(NULL, " ");
}
string res[MaxSize]; //统计的单词列表
int num[MaxSize] = { 0, };
for (int i = 0, j = 0; word[i] != NULL; i++) { //逐个对word中的单词进行处理
bool a = (*word[i] >= ‘a‘ && *word[i] <= ‘z‘) || (*word[i] >= ‘A‘ && *word[i] <= ‘Z‘);
if (a != 1)
continue;
int flag = 0;
for (int k = 0; k < j; k++) { //检查是否已经有
if (res[k].compare(word[i]) == 0) {
num[k]++;
flag = 1;
}
}
if (flag == 0) {
res[j] = word[i];
num[j]++;
j++;
}
}
for (int i = 0; num[i] != 0; i++)
cout << res[i] << " " << setiosflags(ios_base::right)<<num[i] << endl;
return 0;
}
to be or not to be , that is a question
to 2
be 2
or 1
not 1
that 1
is 1
a 1
question 1
原文:https://www.cnblogs.com/Za-Ya-Hoo/p/12680683.html