用c++,统计一个字符串中的单词数量
时间: 2024-03-01 17:55:25 浏览: 39
可以使用C++的标准库函数和算法来实现这个功能。以下是一个简单的例子:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str = "This is a string.";
int count = 1;
for (int i = 0; i < str.size(); i++)
{
if (isspace(str[i]))
count++;
}
cout << "The number of words in the string is: " << count << endl;
return 0;
}
```
这个程序使用了C++的string类来存储输入的字符串,然后使用isspace()函数(在<ctype.h>中定义)来判断空格字符,从而统计单词数量。最后输出结果。
相关问题
统计单词的数量并输出单词的最后一个字符c++
以下是一个简单的 C++ 代码,可以统计输入字符串中单词的数量,并输出每个单词的最后一个字符:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
getline(cin, input); // 读入一行输入字符串
int wordCount = 0;
char lastChar = '\0';
for (char c : input) {
if (c == ' ' || c == '\t' || c == '\n') { // 遇到空格、制表符或换行符,表示一个单词的结束
if (lastChar != '\0') { // 如果上一个字符不是单词分隔符,说明刚刚结束了一个单词
wordCount++;
cout << lastChar << endl; // 输出上一个单词的最后一个字符
lastChar = '\0'; // 重置上一个字符
}
} else {
lastChar = c;
}
}
if (lastChar != '\0') { // 最后一个字符不是单词分隔符,说明最后一个单词还没结束
wordCount++;
cout << lastChar << endl; // 输出最后一个单词的最后一个字符
}
cout << "Total word count: " << wordCount << endl; // 输出单词总数
return 0;
}
```
例子输入:`This is a simple example.`
例子输出:
```
s
s
a
e
Total word count: 5
```
c++检测字符串中重复单词数量并根据字典序排序
你可以使用 C++ 中的 `std::map` 来实现检测字符串中重复单词的数量,并使用 `std::set` 对单词进行字典序排序。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <sstream>
int main() {
std::string str = "the quick brown fox jumps over the lazy dog";
std::istringstream iss(str);
std::map<std::string, int> wordCount;
// 统计单词出现次数
std::string word;
while (iss >> word) {
wordCount[word]++;
}
// 将单词按字典序排序
std::set<std::string> sortedWords;
for (const auto& pair : wordCount) {
sortedWords.insert(pair.first);
}
// 输出结果
for (const auto& word : sortedWords) {
std::cout << word << ": " << wordCount[word] << std::endl;
}
return 0;
}
```
该代码首先将字符串分割为单词,并使用 `std::map` 统计每个单词的出现次数。然后,将单词按字典序插入到 `std::set` 中,最后按顺序输出每个单词及其出现次数。运行以上代码,输出结果为:
```
brown: 1
dog: 1
fox: 1
jumps: 1
lazy: 1
over: 1
quick: 1
the: 2
```
注意,该示例代码仅演示了基本的功能,你可以根据实际需求进行扩展和优化。