0

我想删除字符串中的所有数字(最终是所有符号和空格)并保留字符串中的所有字母字符。我最终要做的是从大块文本中搜索回文。

用我现在得到的东西,它会抹去数字;加上被擦除的第一个数字字符之后的所有其他非数字字符。我想知道为什么这样做,以及我能做些什么来让它只擦除数字字符。

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

int main()
{
bool con = true;
while (con == true)
{
cout << "Enter a string: ";
string input;
getline(cin, input);

/** here is where I am attempting to erase all numeric characters in input string**/    
for(int i=0; i<input.length(); i++){

    if(isdigit(input.at(i))){

        string::iterator it;
        it=input.begin()+i;
        input.erase(i);
    break;
    }
}

string go;

cout << input << endl;

    cout << "Continue? y/n " << endl;
    getline(cin, go);
    if( go != "y")
        con = false;


}
system("pause");
return 0;
}
4

3 回答 3

1
for(int i=0; i<input.length(); i++){

    if(isdigit(input.at(i))){

        string::iterator it;
        it=input.begin()+i;
        input.erase(i);
    break;
    }
}

I don`t like that code snippet: decide that to use iterators or indexes, I think you shoudn`t mix them.
There is error in you code: when you erase from a string it`s length also changes(so for loop will not work, instead use while loop)

string::iterator it = input.begin();

    while (it != input.end())
    {
         while( it != input.end() && isdigit(*it))
         {
              it = input.erase(it);
         }
         if (it != input.end())
             ++it;
    }
于 2013-03-31T03:25:01.050 回答
1
cin >> inputString;
for(string::iterator begin = inputString.begin(), end = inputString.end(); begin != end;){
  if(isdigit(*begin)){
    begin = inputString.erase(begin);
  }else
    ++begin;
}
//cout << inputString;
于 2013-03-31T07:20:09.873 回答
0

I suggest to research how string.erase() works; the version which takes one argument deletes everything after and including the index provided. What should fix your problem is changing input.erase(i) to input.erase(i, 1). The version which takes two arguments deletes an amount of characters equal to the second argument starting at the first arguments position.

Also, I don't see the purpose of these two lines in your program:

string::iterator it;
it=input.begin()+i;
于 2013-03-31T03:25:33.590 回答