3

Quero retirar todos os espaços em branco de uma string, mas não sei como fazer já tentei usar replace mas não deu certo.

2 Respostas 2

2

Tem algoritmo pronto na biblioteca que facilita muito o trabalho:

#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;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

1
  • Funcionou!! estava já a um tempo tentando, muito obrigado! 4/10/2015 às 18:05
0

Contribuindo para esse tema fiz uma mesclagem de C/C++, objetivando retirar os espaços excedentes, tanto no final quanto no meio de uma string. Veja o código que consegui

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);
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .