繁体   English   中英

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

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

试图检查字符串的第一个字符以查看它是否包含“/”。

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

我知道上面的代码不起作用,因为 pathname.at(0) 被认为是一个 int。

我确定这已经被问过了。 但我环顾四周。 我见过 substr 方法、 find 方法和许多其他方法。 我似乎无法让他们正常工作。

建议? 提前致谢。

对字符常量使用单引号

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

双引号,无论里面有多少个字符,都代表一个C 风格的 string 您无法将字符与 C 字符串进行比较。

您将第一个符号代码与指向字符串的指针进行比较。 尝试将第一个符号与字符进行比较。

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

暂无
暂无

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

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