尝试替换字符串中的单词
我试图从输出中获取单词并找到其中包含字母 Q 的任何单词。如果有的话,需要用“坏”这个词来代替。之后,我尝试将每个单词附加到output2。我在做这件事时遇到了麻烦。我编译时得到的错误是:
从“const char*”到“char”的无效转换[-fpermissive]
#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;
}
I am trying to take the words from output and find any word with the letter Q in it. If the word does, it needs to be replaced by the word "bad". After that, I am trying to append each word to output2. I am having trouble doing this. The error I get when I compile is:
invalid conversion from 'const char*' to 'char' [-fpermissive]
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有更简单的方法可以做到这一点:
输出:
但要注意针是新值的子字符串的情况。在这种情况下,您可能需要移动索引以避免无限循环;示例:
输出
There is much easier way how to do that:
output:
But watch out for case when the needle is a substring of the new value. In that case you might want to be shifting the index to avoid an infinite loop; example:
outputs
这是编译错误的原因:
test2[1]
的类型为char
且"bad"
的类型为const char *
:此分配不合法。使用
std::string::replace()
将q
更改为"bad"
:因为您也只需要替换第一次出现的
'q'
(我认为这是基于关于for
循环中的逻辑)您可以将for
循环替换为:编辑:
要替换整个单词:
注意,
output2
将包含包含'q'
的单词当前的逻辑。这是纠正它的一种方法:This is the cause of the compilation error:
test2[1]
is of typechar
and"bad"
is of typeconst char*
: this assignment is not legal.Use
std::string::replace()
to changeq
to"bad"
:As you also only require to replace the first occurrence of
'q'
(I think this based on the logic in thefor
loop) you could replace thefor
loop with:EDIT:
To replace the whole word:
Note,
output2
will contain words if they contain'q'
with the current logic. This would be one way of correcting it: