尝试使用 C++ 从字符串中删除所有非字母字符,鉴于我拥有的代码,最好的方法是什么?

问题描述 投票:0回答:2

我是 C++ 初学者,对该语言还不太熟悉。那么修复我的代码最简单的方法是什么?我认为

userInput.insert(i, "");
有问题,但我不确定是什么。

示例:如果输入为:

-Hello, 1 world$!
输出将是:
Helloworld

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

int main() {
   string userInput;
   string lowerAlpha = "abcdefghijklmnopqrstuvwxyz";
   string upperAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   
   getline(cin, userInput);
   
   for (int i = 0; i < userInput.size(); ++i) {
      for (int j = 0; j < 26; ++j) {
         if ((userInput.at(i) != lowerAlpha.at(j)) || (userInput.at(i) != upperAlpha.at(j))) {
            userInput.insert(i, "");
         }   
      }      
   }
   
   cout << userInput << endl;

   return 0;
}
c++ algorithm for-loop stdstring erase-remove-idiom
2个回答
1
投票

如果您的编译器支持 C++ 20,那么您可以使用标准函数

std::erase_if
和 lambda,例如

#include <string>
#include <cctype>

//...

std::erase_if( userInput, []( unsigned char c ) { return not isalpha( c ); } );

否则使用标准算法

std::remove_if
和成员函数
erase
,例如

#include <string>
#include <iterator>
#include <algorithm>
#include <cctype>

//...

userInput.erase( std::remove_if( std::begin( userInput ),
                                 std::end( userInput ),
                                 []( unsigned char c )
                                 {
                                     return not isalpha( c );
                                 } ), std::end( userInput ) );  

如果将您的方法与 for 循环一起使用,则循环代码可以按以下方式查找

#include <iostream>
#include <string>
#include <string_view>
#include <cctype>

int main() 
{
    const std::string_view lowerAlpha = "abcdefghijklmnopqrstuvwxyz";
    const std::string_view upperAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string userInput = "-Hello, 1 world$!";

    std::cout << userInput << '\n';

    for ( std::string::size_type i = 0; i < userInput.size(); )
    {
        if ( lowerAlpha.find( userInput[i] ) == std::string_view::npos &&
             upperAlpha.find( userInput[i] ) == std::string_view::npos )
        {
            userInput.erase( i, 1 );
        }
        else
        {
            ++i;
        }
    }

    std::cout << userInput << '\n';
}

程序输出为

-Hello, 1 world$!
Helloworld

0
投票

not sure if that's the right way to solve it but I got the desired output

© www.soinside.com 2019 - 2024. All rights reserved.