c++ - 试图修复一个字符串函数,它接受一个字符串并通过替换一些单词来改变它

标签 c++

我正在尝试修复一个函数,它接受一个字符串 a 检查它是否可以找到数字 4 和 5 并将它们更改为 N

#include<iostream>
#include<string>
#include<cstring>
using namespace std;

string Newstring(string& Text);

int main()
{
    while (1)
    {
        string head = "";
        cout << "Input a string: ";
        getline(cin, head);
        cout << '\n';
        cout << "The new string is: ";
        cout << Newstring(head);
        cout << '\n';
        cout << "This is the end";
        cin.ignore();
        system("cls");
    }
    system("pause");
    return 0;
}


string Newstring(string& Text)
{
    string NewText = "";
    for (int i = 0; i < Text.length(); i++)
    {
        if (i == '4' || i == '5')
        {
            i = 'N';
            NewText += Text[i];
        }
    }
    return NewText;
}

输入一个字符串:45fj ji

新的字符串是: 这就是结局 这是输出,它不显示新字符串

最佳答案

您正在检查和更新索引 i 而不是 Text[i]。

检查 Text[i]=='4' && Text[i]=='5' 同时更新 Text[i]='N'

关于c++ - 试图修复一个字符串函数,它接受一个字符串并通过替换一些单词来改变它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56616137/

相关文章:

c++ - OpenGL : glRotatef not working?

c++ - 从类类型到类类型的隐式转换

c++ - 将 C++ 函数转换为递归函数

c++ - 如何通过 getter 函数序列化包含指针的类?

c++ - SFINAE 重复构造函数声明

c++ - 多维数组初始化

c++ - 删除放置或非放置新

c++ - 在 C++ 中立即读取由空格分隔的输入字符串和整数

c++ - EXPECT_CALL(mock, f(N)) vs f(K) 后跟 f(N)

c++ - 并行代码故障排除