I want to fill blank space with %20. Below code does not compile and gives error at line
new_String.append(url.at(j));`
Code:
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));
}
With the suggestions given by users of Stackoverflow I am able to execute my program. Below code works just fine. But the code is awkwardly complex (especially the calculation of trailing blank spaces). Can anyone give me some suggestion to make the code more feasible. The program takes input string and replaces blank character with %20
but the blank character in the end
should be neglected and should not be replaced by %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;
}