简体   繁体   English

查找字符串的第一个字符,然后将其与符号 c++ 进行比较

[英]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.我知道上面的代码不起作用,因为 pathname.at(0) 被认为是一个 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.我见过 substr 方法、 find 方法和许多其他方法。 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 .双引号,无论里面有多少个字符,都代表一个C 风格的 string You can't compare a character to a C-string.您无法将字符与 C 字符串进行比较。

You compare the first symbol code with a pointer to string.您将第一个符号代码与指向字符串的指针进行比较。 Try to compare the first symbol with the char.尝试将第一个符号与字符进行比较。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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