【发布时间】:2018-05-16 01:19:58
【问题描述】:
我有一个程序,它接受字符串并将其转换为 char 数组。我想创建没有正则表达式库的正则表达式,该库接受所有在某处具有aa 的a 和b 字符串。
我下面的代码工作正常,但唯一的问题是它也接受除 a 和 b 以外的字符,例如它也接受 baabss。
您能否帮助更正代码以使其在这种情况下拒绝该字符串?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string input_string;
char char_string[20];
int counter=0;
cout << "type in some input text:$" << endl;
cin >> input_string;
strcpy(char_string, input_string.c_str());
for (int i = 0; i < sizeof(input_string); i++)
{
if(char_string[i]=='a' || char_string[i]=='b'){
switch(char_string[i])
{
case 'a' :
counter++;
break;
case 'b' :
if(counter==1){
counter=0;
}
break;
}
}
}
if(counter==2){
cout << "String accepted" << endl;
}
else{
cout << "String not accepted" << endl;
}
std::cin.get();
system ("PAUSE");
}
【问题讨论】:
-
为什么需要转换成字符数组?
operator[]将与std::string一起使用。 -
我这样做是为了将每个字符与 switch 语句匹配
-
@Inam 问题是如果字符串有外来字符,您不会拒绝该字符串
-
@JakeFreeman...谢谢先生,我现在明白了,我跳过了其他部分,现在它可以工作了
-
@Inam 你能支持我的评论吗?