我负责帮助一年级的学生完成这个项目,我们需要在字符串中找到一个单词,通过另一个给定的单词来改变它。我就是这样写的
#include <iostream>
#include <string>
using namespace std;
void changeWord(string &texto, string wordB, int pos, int sizeA)
{
int auxi;
string antes, depois;
for(auxi = 0; auxi < pos; auxi++)
{
antes[auxi] = texto[auxi];
cout<< "Antes["<< auxi<< "]: "<< antes[auxi]<< endl;
}
for(auxi = 0; auxi+pos+sizeA < texto.length(); auxi++)
{
depois[auxi] = texto[auxi+pos+sizeA];
cout<< "Depois["<< auxi<< "]: "<< depois[auxi]<< endl;
}
cout<< "Antes: "<< antes<< " Depois: "<< depois<< endl;
texto = antes + wordB + depois;
cout<< "Texto:"<< texto<< endl;
}
void findWord(string texto, string wordA, string wordB)
{
int auxi;
for(auxi = 0; auxi < texto.length(); auxi++)
{
cout<< "texto["<< auxi<< "]: "<< texto[auxi]<<" wordA[0]: "<< wordA[0]<< endl;
if(texto[auxi] == wordA[0])
{
int auxj;
for(auxj = 1; auxj < wordA.length() && texto[auxi+auxj] == wordA[auxj]; auxj++)
{
cout<< "texto["<< auxi+auxj<< "]: "<< texto[auxi+auxj]<< " wordA["<< auxj<< "]: "<< wordA[auxj]<< endl;
}
if(auxj == wordA.length())
{
changeWord(texto, wordB, auxi, wordA.length());
}
}
}
}
int main()
{
string texto = "Isto_e_um_texto_qualquer";
string wordA, wordB;
cin >>wordA;
cin >>wordB;
findWord(texto, wordA, wordB);
return 0;
}我希望这能起作用,在某种程度上,它做了我想要的事情,直到我在函数调用'changeWord()‘时尝试输出'antes’和'depois‘字符串。
它们在各自的循环中工作,打印到屏幕上预期的字符:
cout<< "Antes["<< auxi<< "]: "<< antes[auxi]<< endl;
cout<< "Depois["<< auxi<< "]: "<< depois[auxi]<< endl;这不会:
cout<< "Antes: "<< antes<< " Depois: "<< depois<< endl;'antes‘和'depois’都打印为空白。此外,当程序运行到下面这一行时,它会崩溃:
texto = antes + wordB + depois;我假设这是出于同样的原因,它不能在前一行中打印它们。我做错了什么?
发布于 2014-05-20 20:49:42
您的代码中包含。
您将antes和depois都声明为空字符串,然后执行以下操作:
antes[auxi] = texto[auxi];无论您使用什么索引,对于空字符串antes来说,它仍然是越界的。
在该特定循环中,您从零开始索引,因此可以添加以下内容:
antes += texto[auxi];或者使用substr函数代替循环:
antes = texto.substr(0, auxi);而不是谈论现有的replace函数。
发布于 2014-05-20 20:53:08
,
,我们需要在字符串中找到一个单词,用另一个给定的单词来改变它。
我可以建议您使用std::string的内置功能来为您完成繁重的工作吗?
std::string s = "a phrase to be altered";
std::string to_replace = "phrase";
std::string replacement = "sentence";
size_t pos = s.find(to_replace);
if (pos != std::string::npos)
s.replace(pos, to_replace.length(), replacement);https://stackoverflow.com/questions/23760222
复制相似问题