我试图检查字符串末尾的下划线,我有这个代码,但我仍然没有成功。它只检查字符串开头的下划线。 正如我评论的那样,条件检查最后一个字符不在这里......我不知道如何编码...
void Convert(string input){
string output = "";
string flag = "";
bool underscore = false;
bool uppercase = false;
if ( islower(input[0]) == false){
cout << "Error!" <<endl;
return;
}
for (int i=0; i < input.size(); i++){
if ( (isalpha( input[i] ) || (input[i]) == '_') == false){
cout << "Error!" <<endl;
return;
}
if (islower(input[i])){
if (underscore){
underscore = false;
output += toupper(input[i]);
}
else
output += input[i];
}
else if (isupper(input[i])){
if (flag == "C" || uppercase){
cout << "Error!"<<endl;
return;
}
flag = "Java";
output += '_';
output += tolower(input[i]);
}
else if (input[i] == '_'){
if (flag == "Java" || underscore){
cout << "Error!" <<endl;
return;
}
flag = "C";
underscore = true;
}
}
cout << output <<endl
;
}
在字符串/&gt;
的末尾编辑/查找下划线for (int i=input.size()-1; i >=0; i--){
if ( input[i]=='_' ){
cout<<"Chyba"<<endl;
break;
}
}
答案 0 :(得分:3)
如果你想做的就是检查字符串的最后一个元素是否是下划线,那么
if (!input.empty())
return *(input.rbegin()) == '_';
或
if (!input.empty())
return input[input.size()-1] == '_';
答案 1 :(得分:2)
或者在C ++ 11中使用
if (!input.empty())
return input.back() == '_';
答案 2 :(得分:1)
你的逻辑看起来有点奇怪,这可能使它难以理解。让我们重新排列并删除一些括号:
if ( (isalpha( input[i] ) || (input[i]) == '_') == false){
if ( (isalpha( input[i] ) || input[i] == '_' ) == false){
if ( !(isalpha(input[i]) || input[i] == '_') ){
if (! ( isalpha(input[i]) || input[i] == '_' ) ){
请注意,!
表示not
,这使得虚假陈述成立。这与你的==false
完全相同,但是(可以说更清晰)。
所以看起来你说的是:
If this character is an Alpha or an Underscore, don't continue.
但你要问的是:
Is there an underscore at the end of the string?
由于你对字符串的结尾感兴趣,为什么不转换你的for循环?
for (int i=input.size()-1; i >=0; i--){
请注意,由于C ++中的数组是0-based,因此字符串的长度比其末尾大1,所以我们从input.size()-1
字符开始。
那么为什么我们不忽略空格并在我们看到下划线时停止?
for (int i=input.size()-1; i >=0; i--){
if( input[i]==' ' || input[i]=='\t' )
continue;
else if ( isalpha(input[i]) ){
cout<<"String ends with an alpha."<<endl;
break;
} else if ( input[i]=='_' ){
cout<<"String ends with an underscore."<<endl;
break;
}
}
请注意,使用else if
和continue
以及break
可以让您轻松了解此处发生的情况。