C++ 从字符串中删除逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2684491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:21:00  来源:igfitidea点击:

remove commas from string

c++string

提问by Ray

I created a program in C++ that remove commas (,) from a given integer. i.e. 2,00,00would return 20000. I am not using any new space. Here is the program I created:

我在 C++ 中创建了一个程序,用于,从给定的整数中删除逗号 ( )。即2,00,00会返回20000。我没有使用任何新空间。这是我创建的程序:

void removeCommas(string& str1, int len)
{
    int j = 0;

    for (int i = 0; i < len; i++)
    {
        if (str1[i] == ',')
        {
            continue;
        }
        else
        {
            str1[j] = str1[i];
            j++;
        }
    }

    str1[j] = '
Input : 2,000,00
String length  =8
Output = 200000 0
Length = 8
'; } void main() { string str1; getline(cin, str1); int i = str1.length(); removeCommas(str1, i); cout << "the new string " << str1 << endl; }

Here is the result I get:

这是我得到的结果:

#include <algorithm>

str1.erase(std::remove(str1.begin(), str1.end(), ','), str1.end());

My question is that why does it show the length has 8in output and shows the rest of string when I did put a null character. It should show output as 200000and length has 6.

我的问题是为什么它8在输出中显示长度并在我确实放置空字符时显示字符串的其余部分。它应该显示输出200000和长度有6

回答by Fred Larson

Let the standard library do the work for you:

让标准库为您完成工作:

std::string str2(str1.size(), '0');
str2.erase(std::remove_copy(str1.begin(), str1.end(), str2.begin(), ','), str2.end());

If you don't want to modify the original string, that's easy too:

如果您不想修改原始字符串,那也很简单:

std::string s("
void removeStuff(string& str, char character)
{
 size_t pos;
 while( (pos=str.find(character)) != string::npos )
      str.erase(pos, 1);
}

 void main()
{
 string str1;
 getline(cin, str1);
 removeStuff(str1, ',');
 cout<<"the new string "<<str1<<endl;
}
 void fastRemoveStuff(string& str, char character)
{
 size_t len = str.length();
 char *t, *buffer = new char[len];
 const char *p, *q;

 t = buffer, p = q = str.data();
 while( p=(const char*)memchr(q, character, len-(p-q)) ) {
     memcpy(t, q, p-q);
     t += p-q, q = p+1;
 }
 if( q-str.data() != len ) {
     size_t tail = len - (q-str.data());
     memcpy(t, q, tail);
     t += tail;
 }
 str.assign(buffer, t-buffer);
 delete [] buffer;
}

 void main()
{
 string str1 = "56,4,44,55,5,55"; // should be large, 10^6 is good
 // getline(cin, str1);
 cout<<"the old string " << str1 << endl;
 fastRemoveStuff(str1, ',');
 cout<<"the new string " << str1 << endl;
}
", 2); assert(s.size() == 2);

回答by Brian R. Bondy

You need to do a resize instead at the end.

您需要在最后进行调整大小。

Contrary to popular belief an std::string CAN contain binary data including 0s. An std::string 's .size()is not related to the string containing a NULL termination.

与流行的看法相反, std::string 可以包含包括 0 在内的二进制数据。std::string.size()与包含 NULL 终止的字符串无关。

#include <string>
#include <cassert>

using namespace std;

string Remove( const string & s, char c  ) {

    string r;
    r.reserve( s.size() );

    for ( unsigned int i = 0; i < s.size(); i++ ) {
        if ( s[i] != c ) {
            r += s[i];
        }
    }

    return r;
}

int main() {
    assert( Remove( "Foo,Bar,Zod", ',' ) == "FooBarZod" );
}

回答by Kaz Dragon

The answer is probably that std::strings aren't NUL-terminated. Instead of setting the end+1'th character to '\0', you should use str.resize(new_length);.

答案可能是std::strings 不是以 NUL 结尾的。而不是将 end+1'th 字符设置为 '\0',您应该使用str.resize(new_length);.

Edit: Also consider that, if your source string has no commas in it, then your '\0' will be written one past the end of the string (which will probably just happen to work, but is incorrect).

编辑:还要考虑一下,如果您的源字符串中没有逗号,那么您的 '\0' 将被写入字符串末尾(这可能恰好可以工作,但不正确)。

回答by Draco Ater

The std::srting does not terminate with \0, you are mixing this with char* in C. So you should use resize.

std::srting 不以 终止\0,您将其与 C 中的 char* 混合。因此您应该使用resize

回答by rubber boots

The solution has already been posted by Fred L.

解决方案已经由 Fred L 发布。

In a "procedural fashion" (without "algorithm") your program would look like:

以“程序方式”(没有“算法”),您的程序将如下所示:

void main()
{
  int  i ;
  char  n[20] ;

  clrscr() ;

  printf("Enter a number. ") ;
  gets(n) ;

  printf("Number without comma is:") ;
  for(i=0 ; n[i]!='
for (int x = 0; x < (m_wMapWidth / (TileSize / 2)); x++) {
    for (int y = 0; y < (m_wMapHeight / (TileSize / 2)); y++) {
        if (ss >> str) {


            for (int strIterator = 0; strIterator < str.length(); strIterator++) {
                if (str[strIterator] == ',') {`

                    Here we need to define the size of the string we want to extract after the previous comma and before the next comma

                    `strSize = strIterator - strStartPos;`
' ; i++) if(n[i] != ',') putchar(n[i]) ; getch(); }

then.

然后。

Regards

问候

rbo

红包

EDIT / Addendum:

编辑/附录:

In order to adress some efficiency concerns of readers, I tried to come up with the fastest solution possible. Of course, this should kick in on string sizes over about 10^5 characters with some characters to-be-removed included:

为了解决读者的一些效率问题,我试图想出最快的解决方案。当然,这应该适用于超过 10^5 个字符的字符串大小,其中包括一些要删除的字符:

                    `m_wMapPointInfo[x][y][arrayPointInfoDepth] = str.substr(strStartPos, strSize);`

回答by rubber boots

My own procedural version:

我自己的程序版本:

                    arrayPointInfoDepth++;

                    if (arrayPointInfoDepth == WorldMapPointInfos) {
                        strStartPos = 0;
                        arrayPointInfoDepth = 0;
                        break;
                    }
                }
            }
        }



    }
}

回答by Dilip Kumar Yadav

Here is the program:

这是程序:

int strStartPos = 0;
int strSize = 0;
int arrayPointInfoDepth = 0;

for (int x = 0; x < (m_wMapWidth / (TileSize / 2)); x++) {
    for (int y = 0; y < (m_wMapHeight / (TileSize / 2)); y++) {
        if (ss >> str) {


            for (int strIterator = 0; strIterator < str.length(); strIterator++) {
                if (str[strIterator] == ',') {
                    strSize = strIterator - strStartPos;

                    m_wMapPointInfo[x][y][arrayPointInfoDepth] = str.substr(strStartPos, strSize);

                    strStartPos = strIterator + 1;

                    arrayPointInfoDepth++;

                    if (arrayPointInfoDepth == WorldMapPointInfos) {
                        strStartPos = 0;
                        arrayPointInfoDepth = 0;
                        break;
                    }
                }
            }
        }



    }
}

For detailed description you can refer this blog: http://tutorialsschool.com/c-programming/c-programs/remove-comma-from-string.php

有关详细说明,您可以参考此博客:http: //tutorialsschool.com/c-programming/c-programs/remove-comma-from-string.php

The same has been discussed in this post: How to remove commas from a string in C

这篇文章也讨论了同样的问题:如何从 C 中的字符串中删除逗号

回答by toshito

Well, if youre planing to read from a file using c++. I found a method, while I dont think thats the best method though, but after I came to these forums to search for help before, I think its time to contribute with my effort aswell.

好吧,如果您打算使用 C++ 从文件中读取。我找到了一个方法,虽然我不认为那是最好的方法,但是在我之前来到这些论坛寻求帮助之后,我认为是时候贡献我的努力了。

Look, here is the catch, what I'm going to present you is part of the source code of the map editor Im building on right now, that map editor obviously has the purpose to create maps for a 2D RPG game, the same style as the classic Pokemon games for example. But this code was more towards the development of the world map editor.

看,这里是重点,我要向您展示的是我现在正在构建的地图编辑器的源代码的一部分,该地图编辑器显然旨在为 2D RPG 游戏创建地图,相同的风格以经典的口袋妖怪游戏为例。但是这段代码更倾向于世界地图编辑器的开发。

`int strStartPos = 0; int strSize = 0; int arrayPointInfoDepth = 0;

`int strStartPos = 0; int strSize = 0; int arrayPointInfoDepth = 0;

##代码##

And here, we do the actual transformation, we give to the vector that is a 3D vector btw the string we want to extract at that moment

在这里,我们进行了实际的转换,我们给了一个 3D 向量的向量 btw 我们想在那一刻提取的字符串

##代码##

And here, we just define that starting position for the next small piece of the string we want to extract, so the +1 means that after the comma we just passed strStartPos = strIterator + 1;

在这里,我们只是为我们要提取的下一小段字符串定义了起始位置,所以 +1 表示在我们刚刚传递的逗号之后 strStartPos = strIterator + 1;

Here, well since my vector has only 6 postions that is defined by WorldMapPointInfos we need to increment the third dimension of the array and finally do a check point where if the info has arrived the number 6 then break the loop

在这里,因为我的向量只有 6 个由 WorldMapPointInfos 定义的位置,所以我们需要增加数组的第三维,最后做一个检查点,如果信息到达数字 6,则中断循环

##代码##

Either way on my code, think abt that the vector is just a string, thats all you need to know, hope this helps though :/

无论哪种方式在我的代码中,都认为向量只是一个字符串,这就是您需要知道的全部内容,但希望这会有所帮助:/

Full view:

全视图:

##代码##