3
I want to remove all blank spaces from one string, but I don’t know how to do I’ve tried to use replace but it didn’t work out.
3
I want to remove all blank spaces from one string, but I don’t know how to do I’ve tried to use replace but it didn’t work out.
2
Has algorithm ready in the library that makes the work much 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;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
0
Contributing to this theme I mixed C/C++, aiming to remove the excess spaces, both at the end and in the middle of a string. Look at 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] = '\0';
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] = '\0';
output.clear();
output.append(out);
return(output);
}
							Browser other questions tagged c++ string
You are not signed in. Login or sign up in order to post.
It worked!! I’ve been trying for a while, thank you very much!
– Roger Amaro Almeida