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'