简体   繁体   English

在C ++中删除字符串中的空格

[英]Remove spaces from a string in C++

I am currently learning C++. 我目前正在学习C ++。 I am trying to code a method to remove white spaces form a string and return the string with no spaces This is my code: 我正在尝试编写一个方法来从字符串中删除空格并返回没有空格的字符串这是我的代码:

string removeSpaces(string input)
{
  int length = input.length();
  for (int i = 0; i < length; i++) {
     if(input[i] == ' ')
        input.erase(i, 1);
  }
  return input
}

But this has a bug as it won't remove double or triple white spaces. 但这有一个错误,因为它不会删除双或三个空格。 I found this on the net 我在网上发现了这个

s.erase(remove(s.begin(),s.end(),' '),s.end());

but apparently this is returning an iterator (if I understand well) Is there any way to convert the iterator back to my string input ? 但显然这是返回一个iterator (如果我理解的话)有没有办法将iterator转换回我的字符串input Most important is this the right approach? 最重要的是这是正确的方法吗?

std::string::erase returns an iterator, but you don't have to use it. std::string::erase返回一个迭代器,但你不必使用它。 Your original string is modified. 您的原始字符串已被修改。

string removeSpaces(string input)
{
  input.erase(std::remove(input.begin(),input.end(),' '),input.end());
  return input;
}

std::remove_if along with erase would be much easier ( see it live ): std :: remove_if以及erase会更容易( 看到它直播 ):

input.erase(remove_if(input.begin(), input.end(), isspace),input.end());

using std::isspace had the advantage it will capture all types of white space. 使用std :: isspace有利于它捕获所有类型的空白区域。

Let's assume your input has a double space, for example "c++[ ][ ]is[ ]fun" ( [ ] represents a single space). 假设您的输入具有双倍空格,例如“c ++ [] []是[] fun”( [ ]表示单个空格)。 The first space has index 3 (numeration starts from 0) and the second space, is of course index 4. 第一个空格有索引3(编号从0开始),第二个空格当然是索引4。

In your for loop, when you hit i == 3 you erase the first space. 在你的for循环中,当你点击i == 3你会删除第一个空格。 The next iteration of the loop takes i == 4 as the index. 循环的下一次迭代需要i == 4作为索引。 But is the second space at index 4 now ? 但现在是指数4的第二个空间吗? No! 没有! Removing the first space changed the string into "c++[ ]is[ ]fun": the space to remove is at index 3, again! 删除第一个空格将字符串更改为“c ++ [] is [] fun”:要删除的空间再次位于索引3处!

The solution can be to remove spaces right-to-left: 解决方案可以是从右到左删除空格:

for (int i = length-1; i >= 0; --i) {
   if(input[i] == ' ')
      input.erase(i, 1);
}

This solution has the benefit of being simple, but as Tony D points out, it's not efficient. 这种解决方案具有简单的优点,但正如Tony D指出的那样,它效率不高。

this should also work -- std::replace( input.begin(), input.end(), ' ', ''); 这也应该工作 - std::replace( input.begin(), input.end(), ' ', ''); You need to include <algorithm> 您需要包含<algorithm>

this code should work 这段代码应该有效

string removeSpaces(string input)
{
  int length = input.length();
  for (int i = 0; i < length; i++) {
     if(input[i] == ' ')
     {
        input.erase(i, 1);
         length--;
         i--;
     }
  }
  return input
}

Reason: if it gets space in the string it will reduce the length of the string, so you have to change the variable: "length" accordingly. 原因:如果它在字符串中获得空间,它将减少字符串的长度,因此您必须相应地更改变量:“length”。

I tried to write something to. 我试着写点东西。 This function take a string and copy to another temporary string all the content without extra spaces. 此函数接受一个字符串并将所有内容复制到另一个临时字符串,而不包含额外空格

std::string trim(std::string &str){
int i = 0;
int j = 0;
int size = str.length();
std::string newStr;
bool spaceFlag = false;

for(int i = 0;i < size; i++){
    if(str[i] == ' ' && (i+1) < size && str[i+1] == ' '){
        i++;
        spaceFlag = true;
        continue;
    }       
    if(str[i] == ' '){
        newStr += " ";
        continue;
    }
    if(str[i] == '\t' && i != 0){
        str[i] = ' ';
        newStr += " ";
    }
    else{
        newStr += str[i];
        if(spaceFlag){
            newStr += " ";
            spaceFlag = false;
        }
    }
}
str = newStr;

return str;

} }

#include<iostream>
#include<string.h>
using namespace std;

void trimSpace(char s[])
{
    int i=0, count=0, j=0;

    while(s[i])
    {
        if(s[i]!=' ')
            s[count++]=s[i++];
        else {
            s[count++]=' ';

            while(s[i]==' ')
                i++;
        }       
    }   

    s[count]='\0';
    cout<<endl<<"  Trimmed String : ";  
    puts(s);
}

int main()
{
    char string[1000];
    cout<<"  Enter String : ";
    gets(string);
    trimSpace(string);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM