c++字符串分割处理代码,要求输入英文句子“This is a string”并存入数组,要求以数字菜单的形式列出程序的主要功能
时间: 2024-03-05 10:52:32 浏览: 157
以下是一个C++字符串分割处理的代码示例,可以实现输入英文句子并将其分割成单词存入数组中:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> splitString(string str) {
vector<string> res;
string word = "";
for (auto x : str) {
if (x == ' ') {
res.push_back(word);
word = "";
} else {
word = word + x;
}
}
res.push_back(word);
return res;
}
int main() {
string input;
cout << "Enter a sentence: ";
getline(cin, input);
vector<string> words = splitString(input);
cout << "Menu:\n";
cout << "1. Display the sentence\n";
cout << "2. Display the number of words in the sentence\n";
cout << "3. Display all the words in the sentence\n";
cout << "4. Exit\n";
int choice;
do {
cout << "Enter your choice (1-4): ";
cin >> choice;
switch (choice) {
case 1:
cout << "Sentence: " << input << endl;
break;
case 2:
cout << "Number of words: " << words.size() << endl;
break;
case 3:
cout << "Words: ";
for (auto word : words) {
cout << word << " ";
}
cout << endl;
break;
case 4:
cout << "Exiting program...\n";
break;
default:
cout << "Invalid choice. Please enter a number between 1 and 4.\n";
break;
}
} while (choice != 4);
return 0;
}
```
该程序的主要功能如下:
1. 显示输入的句子;
2. 显示句子中单词的数量;
3. 显示句子中的所有单词;
4. 退出程序。
阅读全文
相关推荐
















