簡體   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