2014-09-22 47 views
-6

問題:我在傳遞字符串時發現問題,並找出該字符串中的單詞。如何查找字符串中的特定字詞

我曾嘗試下面的代碼:

if(string.find("Z03")) 
{ 
    // field exists 
    return true; 
} 

字符串:Z030000000057

這裏就是我想要做的事:

if(string.find("Z03")) 
{ 
    // field exists 
    return true; 
} 

當我喜歡「的信息傳遞字符串; Z030000000057 「然後它進入循環,但當我只是通過」Z030000000057「它進入循環。

請幫助我。

+3

閱讀[一些文檔](http://en.cppreference.com/w/cpp/string/basic_string/find)。 – juanchopanza 2014-09-22 11:59:54

+1

查找不返回布爾值,它返回找到該字符串的位置的索引。你隱式地將int轉換爲bool。 [見文檔](http://en.cppreference.com/w/cpp/string/basic_string/find) – Borgleader 2014-09-22 12:00:00

+0

是什麼循環? – 2014-09-22 12:04:43

回答

2

find()返回的第一次出現,或string::npos的索引。如果find()返回零(即在字符串開頭的第一個匹配項)或不匹配(即,搜索字符串稍後發生,或根本不發生),則您的if正在測試。

您是可能尋找...

if (string.find("Z03") != std::string::npos) 
{ 
    // field exists 
    return true; 
} 

...這或許可以縮短爲...

return (string.find("Z03") != std::string::npos); 

...如果既不是真也不假分支做別的事情。

0

檢查在「查找」方法的文檔:http://en.cppreference.com/w/cpp/string/basic_string/find

該方法返回找到字符串或std ::字符串::如果子沒有找到非營利組織的第一個字符的位置。

關於你提到的例子:

std::string s("Z030000000057"); 
if(s.find("Z03")) 
{ 
    // execution DOES NOT goes here because find returns 0 as found position 
} 

s = ";Z030000000057"; 
if(s.find("Z03")) 
{ 
    // execution goes here because find returns 1 as found position 
} 

正確的代碼是:

if (s.find("Z03") != std::string::npos) 
{ 
    // field exists 
} 

我建議使用cppreference作進一步檢查的標準功能,這是非常有用的。