簡體   English   中英

cpp字符串find()無法按預期工作-返回大垃圾值

[英]cpp string find() doesnt work as expected - returns big junk values

我正在嘗試使用find()在另一個字符串中查找子字符串的索引,但是如果該子字符串不存在,則會得到一個垃圾值,而不是std :: npos。

這是代碼:

字符串output1 =“ abcd”;

cout << output.find(“ gf”)<< endl;

這是輸出:

18446744073709551615

可以防止這種行為嗎? 還有另一種查找子字符串的方法嗎?

(實際上,我只需要查找是否包含子字符串)

謝謝

它返回的是字符串npos的size_t ,因為它找不到您的字符或文本。 您可以改為:

std::size_t found = str.find("findme");

if (found != std::string::npos)
    std:cout << found << std::endl;
else
    std::cout << "String not found" << std::endl // If not found

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM