在c++中使用字符串(搜索字符串,分割字符串,cout<<字符串)
Using strings in C++ (search in string, split string, cout<< string)
我负责帮助一年级学生完成这个项目,我们需要在一个字符串中找到一个单词,并用另一个给定的单词来改变它。我是这样写的
#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'字符串。
它们在各自的循环中工作,向屏幕打印期望的char:
cout<< "Antes["<< auxi<< "]: "<< antes[auxi]<< endl;
cout<< "Depois["<< auxi<< "]: "<< depois[auxi]<< endl;
cout<< "Antes: "<< antes<< " Depois: "<< depois<< endl;
'antes'和'depois'都打印为空白。此外,当到达这一行时,程序会崩溃:
texto = antes + wordB + depois;
我认为这是出于同样的原因,它不能在前一行中打印它们。我做错了什么?
你的代码中有未定义行为
将antes
和depois
声明为空字符串,然后执行如下操作:
antes[auxi] = texto[auxi];
不管你使用什么索引,它仍然是越界对于空字符串antes
。
在这个特定的循环中,你从0开始索引,所以你可以添加:
antes += texto[auxi];
或者使用substr
函数代替循环:
antes = texto.substr(0, auxi);
不谈现有的replace
功能
我们需要在一个字符串中找到一个单词,然后用另一个给定的单词来改变它。
我可以建议你使用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);
相关文章:
- 如何在C++中从字符串中分割字符
- 由cin中的字符串中未捕获空白引起的分割错误
- 按分度分割字符串
- 分割故障:核心倾倒C 矢量对字符串:
- C - 返回字符串时的分割故障
- 在结构中使用字符串时的分割故障
- 为什么当从递归函数返回字符串到C 中的Main时,我会得到分割错误
- 在字符串中计数字符出现时,C 分割故障
- 简单的字符串分配导致分割故障
- 试图进入字符串时的分割故障
- 分割故障添加了两个表示字符串的大数字
- 我应该使用哪个函数来分割字符串
- 如何使用STL分割字符串
- C++如何使用多个分隔符分割字符串流
- 使用循环将字符串分割为特定长度的子单元
- 将字符串分割为字符串向量时出现无效转换错误
- 将一行(字符串)分割成更多的字符串
- c++字符串分割和操作
- 字符串分割错误
- 将字符串分割或修剪成一行