试图替换字符串中的单词
Trying to replace words in a string
我正在尝试从输出中提取单词,并找到其中包含字母Q的任何单词。如果该单词包含字母Q,则需要用单词"bad"替换它。之后,我尝试将每个单词附加到output2。我做这件事有困难。我编译时得到的错误是:
从"const char*"到"char"的转换无效[-fpermission]
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;
string manipulate(string x);
int main(int argc, char* argv[])
{
string input, temp, output, output2, test, test2;
int b;
cout << "Enter a string: ";
getline(cin, input);
istringstream iss(input);
while (iss >> test)
{
if(test.length() != 3)
{
test.append(" ", 1);
output.append(test);
}
}
istringstream iss2(output);
while (iss2 >> test2)
{
for(int i = 0; i<test2.length(); i++)
{
switch(test2[i])
{
case 'q':
test2[1]="bad";
output2.append(test2);
break;
}
}
}
cout << "Your orginal string was: " << input << endl;
cout << "Your new string is: " << output2 << endl;
cin.get();
return 0;
}
有一种更简单的方法:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s("Your homework is bad. Really bad.");
while (s.find("bad") != string::npos)
s.replace(s.find("bad"), 3, "good");
cout << s << endl;
return 0;
}
输出:
Your homework is good. Really good.
但要注意指针是新值的子字符串的情况。在这种情况下,您可能希望移动索引以避免无限循环;示例:
string s("Your homework is good. Really good."),
needle("good"),
newVal("good to go");
size_t index = 0;
while ((index = s.find(needle, index)) != string::npos) {
s.replace(index, needle.length(), newVal);
index += newVal.length();
}
cout << s << endl;
输出
Your homework is good to go. Really good to go.
这是编译错误的原因:
test2[1]="bad";
test2[1]
属于char
类型,"bad"
属于const char*
类型:此分配不合法。
使用std::string::replace()
将q
更改为"bad"
:
test2.replace(i, 1, "bad");
由于您只需要替换第一次出现的'q'
(我认为这是基于for
循环中的逻辑),因此可以将for
循环替换为:
size_t q_idx = test2.find('q');
if (std::string::npos != q_idx)
{
test2.replace(q_idx, 1, "bad");
output2.append(test2);
}
编辑:
替换整个单词:
test2 = "bad";
注意,如果output2
包含具有当前逻辑的'q'
,则它们将包含字。这将是纠正它的一种方法:
output2.append(std::string::npos != test2.find('q') ? "bad" : test2);
相关文章:
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- C++-字符串是否包含一个带有简单循环的单词
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 替换字符串中的单词,但忽略引号中的单词
- 替换字符串位置 X 中的单词C++
- 视觉C++使用 map 来比较字符串中的每个单词
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 输出返回编号。等于输入字符串的单词的字符串数
- 在字符串的每个单词的末尾插入字符串
- 分析字符串中的双精度和单词
- 如何使用运算符>>在自定义字符串中输入多个单词?
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- 从文件 (C++) 输入两个单词字符串
- 在一行中输入具有其他输入类型的多个单词字符串
- 打印以 "a" 开头的单词(字符串中)
- 如何让我的代码以不会切断单词(字符串)的方式运行?
- 句子变成单词c++字符串