C++ 从字符串中删除偶数编号的单词
C++ Remove Evenly numbered words from a string
在实现一个家庭作业问题的逻辑时遇到一些问题。我目前使用的平台是Visual Studio 2013,是初学者。我们使用应用程序内置的终端(命令提示符)来获取输入和输出。我们目前使用的是"CIN"和"COUT"。问题如下:
"编写一个程序,要求用户输入一个句子,然后去掉每个偶数单词。例如:"所有总统男人"将变成"所有总统"。使用输出参数将修改后的句子返回到 main() 函数,然后显示原始句子和修改后的句子"。
我一直在尝试将其应用于将每个单词放入数组/向量的逻辑中,并删除每个具有偶数索引的单词。我还没有成功地做到这一点,正在向你们的专家寻求一些帮助!
多谢。
现场演示
std::string line;
// get input from cin stream
if (std::getline(cin, line)) // check for success
{
std::vector<std::string> words;
std::string word;
// The simplest way to split our line with a ' ' delimiter is using istreamstring + getline
std::istringstream stream;
stream.str(line);
// Split line into words and insert them into our vector "words"
while (std::getline(stream, word, ' '))
words.push_back(word);
if (words.size() % 2 != 0) // if word count is not even, print error.
std::cout << "Word count not even " << words.size() << " for string: " << line;
else
{
//Remove the last word from the vector to make it odd
words.pop_back();
std::cout << "Original: " << line << endl;
std::cout << "New:";
for (std::string& w : words)
cout << " " << w;
}
}
你可以写这样的东西
int count = -1;
for (auto it =input.begin();it!=input.end();){
if(*it==' '){
count++;it++;
if (count%2==0){
while (it != input.end()){
if (*it==' ')break;
it=input.erase (it);
}
}else it++;
}else it++;
}`
相关文章:
- 文本文件中的单词链表
- 在指针的帮助下,文本文件中单词的频率
- 如何根据单词在文本中出现的概率输出单词
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 使用if-else将数字转换为单词
- C++-字符串是否包含一个带有简单循环的单词
- 使用单词"not"作为C ++类的名称会导致VS2019错误
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- 如何在数组中找到最小编号的索引号?
- C++为一串单词添加空格
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 贪婪算法编号列表
- 输出返回编号。等于输入字符串的单词的字符串数
- 拼写检查器,单词的唯一编号
- C++ 从字符串中删除偶数编号的单词