简体   繁体   中英

Find first character of string, then compare it with a symbol c++

Attempting to check the first character of a string to see if it contains a "/".

string pathname = "/test";
if(pathname.at(0) == "/")
{
    // if first character is a slash then delete the slash
    // but only delete the slash if it's the first character
    pathname.erase(pathname.begin()+0);
}

I understand that the above code will not work because pathname.at(0) is considered an int.

I'm sure this has been asked before. But I have looked around a lot. I've seen the substr method the find method and many others. I can't seem to get them working right though.

Suggestions? Thanks in advance.

Use single quote for character constant.

if(pathname.at(0) == '/')
                     ^ ^

Double quotes, no matter how many characters are inside, represents a C-style string . You can't compare a character to a C-string.

You compare the first symbol code with a pointer to string. Try to compare the first symbol with the char.

if(pathname.at(0) == '/')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM