在c++中使用字符串(搜索字符串,分割字符串,cout<<字符串)

Using strings in C++ (search in string, split string, cout<< string)

本文关键字:字符串 分割 cout 搜索 c++      更新时间:2023-10-16

我负责帮助一年级学生完成这个项目,我们需要在一个字符串中找到一个单词,并用另一个给定的单词来改变它。我是这样写的

#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;

我认为这是出于同样的原因,它不能在前一行中打印它们。我做错了什么?

你的代码中有未定义行为

antesdepois声明为字符串,然后执行如下操作:

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);