我是 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++ 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