Skip to content

checking for a character on the end of a string

An answer to this question on Stack Overflow.

Question

Im trying to check for underscore on the end of a string, I have this code but Im still not sucessfull with it. It is checking only for the underscore on the beginning of the string. as I commented, condition checking last character is not here...I dont know how to code it in..

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
;

}

edit /looking for underscore on the end of string/>

for (int i=input.size()-1; i >=0; i--){
         if ( input[i]=='_' ){
         cout<<"Chyba"<<endl;
         break;
         } 
     }

Answer

Your logic looks kinda weird, and that might be making it difficult to understand. Let's rearrange it and remove some brackets:

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] == '_' ) ){

Note that the ! means not, which makes a false statement true. This does the same thing as your ==false, but in an (arguably clearer way).

So it looks like what you're saying is:

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

But what you are trying to ask is:

Is there an underscore at the end of the string?

Since you're interested in the end of the string, why not reverse your for-loop?

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

Note that since arrays in C++ are 0-based, the length of the string is 1 greater than its end, so we start at the input.size()-1 character.

Then why don't we ignore blank spaces and stop if we see an underscore?

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;
  }
}

Note that the use of else if and continue and break makes it very easy to follow what's going on here.