gpt4 book ai didi

c++ - 用 %20 忽略所有尾随空格的空白字符的字符串替换

转载 作者:行者123 更新时间:2023-11-30 03:58:09 29 4
gpt4 key购买 nike

我想用 %20 填充空白。下面的代码无法编译并在行中给出错误

new_String.append(url.at(j));`

代码:

void main()
{
string url = "abcde";
string new_String;
for (int j = 0; j < url.length(); ++j)
{
if (url.at(j) == ' ')
{
new_String.append("%20");
}
else
new_String.append(url.at(j));
}

根据 Stackoverflow 用户的建议,我能够执行我的程序。下面的代码工作得很好。但是代码非常复杂(尤其是尾随空格的计算)。谁能给我一些建议,使代码更可行。该程序接受输入字符串并用 %20 替换空白字符,但 end 中的空白字符应忽略,不应替换为 %20

#include"iostream"
using namespace std;
#include"string"
void main()
{
string url = "ta nuj ";
int count = 1; // it holds the blank space present in the end
for (int i = 0; i < url.length(); i++) // this is written to caculate the blank space that //are at the end
{
if (url.at(i) == ' ')
{
for (int k = i + 1; k < url.length(); k++)
{
if ((int)url.at(k) != 32)
{
count = 1;
break;
}
else
{
count++;
i++;
}
}
}
}
string newUrl;

for (int j = 0; j < url.length()-count; j++)
{
if (url.at(j) == ' ')
{
newUrl.append("%20");
}
else
newUrl += (url[j]);
}
cout << "\nThe replaced url is:" << newUrl;
}

最佳答案

打开手册会告诉你 string::append() 只接受一个字符串作为输入,所以你可能想要:

new_String += string(url[j]);

附带说明一下,您不需要现代 C++ 中的所有样板文件(appendat、整数循环)。

关于c++ - 用 %20 忽略所有尾随空格的空白字符的字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27596864/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com