I want to remove all the blanks from a string , but I do not know how to do it already tried to use replace
but did not work.
I want to remove all the blanks from a string , but I do not know how to do it already tried to use replace
but did not work.
Has algorithm ready in the library that makes the job a lot easier:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = " texto com espaços em branco ";
str.erase(remove(str.begin(), str.end(), ' '), str.end());
cout << str;
return 0;
}
See running on ideone .
Contributing to this theme I made a blend of C / C ++, aiming to remove excess spaces, both at the end and middle of a string. See the code I got
string RemoveEspaco(string str)
{
int i, j;
char *input, *out;
string output;
input = new char[str.length()+1];
strcpy(input,str.c_str());
for (i=strlen(input); i > 0; i--)
{
if (input[i] != ' ')
{
break;
}
}
input[i] = 'string RemoveEspaco(string str)
{
int i, j;
char *input, *out;
string output;
input = new char[str.length()+1];
strcpy(input,str.c_str());
for (i=strlen(input); i > 0; i--)
{
if (input[i] != ' ')
{
break;
}
}
input[i] = '%pre%';
out = new char[strlen(input)+1];
for (i=0,j=0;i < strlen(input); i++)
{
if (i > 1)
{
if (input[i] != ' ')
{
out[j] = input[i];
j++;
}
else
{
if ((input[i] == ' ')&&(input[i-1] != ' '))
{
out[j] = input[i];
j++;
}
}
}
else
{
out[j] = input[i];
j++;
}
}
out[j] = '%pre%';
output.clear();
output.append(out);
return(output);
}
';
out = new char[strlen(input)+1];
for (i=0,j=0;i < strlen(input); i++)
{
if (i > 1)
{
if (input[i] != ' ')
{
out[j] = input[i];
j++;
}
else
{
if ((input[i] == ' ')&&(input[i-1] != ' '))
{
out[j] = input[i];
j++;
}
}
}
else
{
out[j] = input[i];
j++;
}
}
out[j] = '%pre%';
output.clear();
output.append(out);
return(output);
}