检查字符串末端的字符

checking for a character on the end of a string

本文关键字:字符 字符串 检查      更新时间:2023-10-16

im试图检查字符串末端的下划线,我有此代码,但我仍然没有成功。它仅检查字符串开头的下划线。正如我评论的那样,检查最后一个字符不在这里...我不知道如何在..

中编码它。
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
;

}

在字符串/>

的末尾编辑/寻找下划线
for (int i=input.size()-1; i >=0; i--){
         if ( input[i]=='_' ){
         cout<<"Chyba"<<endl;
         break;
         } 
     }

如果您要做的就是检查字符串的最后一个元素是否是下划线,则

if (!input.empty())
  return *(input.rbegin()) == '_';

if (!input.empty())
  return input[input.size()-1] == '_';

或在C 11中使用Back

if (!input.empty())
  return input.back() == '_';

您的逻辑看起来有点奇怪,这可能使它很难理解。让我们重新排列并删除一些括号:

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语句正确。这与您的==false一样,但以(可以说是清晰的方式)。

所以您的意思是:

If this character is an Alpha or an Underscore, don't continue.

但是您要问的是:

Is there an underscore at the end of the string?

由于您对字符串的末尾感兴趣,为什么不逆转您的前面?

for (int i=input.size()-1; i >=0; i--){

请注意,由于C 中的数组是基于0的数组,因此字符串的长度大于其末端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 ifcontinuebreak的使用使您可以轻松地遵循此处发生的事情。