第一题:针对只包含数字,字母以及6个特殊字符的字符串,只验字母A~z以及[]^_’ 6个特殊字符部分才是有效的,提取1Ct3r4ip_ti4C6k9Et^:正确的优惠券码:Ctrip_tiCkEt^
[ 91
\ 92
] 93
^ 94
_ 95
’ 96
a~z 97~122
A~Z 65~90
满足条件的这些字符正好是连续的ASCII值,因此只用一句if语句就可以将多余的字符给过滤掉。
#include<iostream>
#include<string>
using namespace std;
int main(){
string str;
cin>>str;
const char *beforechars = str.c_str();
int L = str.length();
char *afterchars=new char[L];
int j = 0;
for(int i = 0; i < str.length(); i ++){
if(beforechars[i] >= 'A' && beforechars[i] <= 'z'){
afterchars[j ++] = beforechars[i];
}
}
for(int i = 0; i < j; i ++){
cout<<afterchars[i];
}
return 0;
}
也可以用正则表达式来做,因此此题目要求只过滤掉数字,此种做法比较局限,但对此题也是可行的。下面给出java代码
public class Main{
public static void main(String[] args){
String str="1Ct3r4ip_ti4C6k9Et^";
System.out.println(str.replaceAll("\\d+",""));
}
}