c++ - 当没有字符串匹配时,在 String 中查找函数会输出垃圾

标签 c++ string function output

我有以下代码:-

    string name = "hello world";
    size_t find = name.find("world");

    if (find != string::npos) {
        cout<<"match found at "<<find;
    }
    else{
        cout<<find;
    }

该程序运行良好,并按预期打印 6 个输出。

但是如果我将其更改为 size_t find = name.find('\n'); 它将垃圾值打印为 18446744073709551615。 find函数在没有找到匹配的字符串时会打印垃圾值吗??

最佳答案

引自http://www.cplusplus.com/reference/string/string/find/

Return Value

The position of the first character of the first match. If no matches were found, the function returns string::npos.

size_t is an unsigned integral type (the same as member type string::size_type).

因此,您的函数会打印 std::string::npos,例如在 MSVS std 库实现中是

basic_string<_Elem, _Traits, _Alloc>::npos =
        (typename basic_string<_Elem, _Traits, _Alloc>::size_type)(-1);

64 位系统上的最大 unsigned int 值是:18,446,744,073,709,551,615,请参阅 https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx

您可以将代码更改为

string name = "hello world";
size_t find = name.find("world");

if (find != string::npos) {
    cout<<"match found at "<<find;
}
else {
    cout<<"match not found";
}

关于c++ - 当没有字符串匹配时,在 String 中查找函数会输出垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37476994/

相关文章:

C 编程 : Initialize pointer to char array inside a function

java - 比较 Java 的 lambda 表达式和 Swift 的函数类型

c++ - 递归打印星形图案

c++ - 使用自己的结构在头类中定义函数?

c++ - int a是什么类型的定义?

java - String#equals 和 String#contentEquals 方法的区别

python - 递归调用返回自身迭代器的对象方法

c++ - Arduino Sublime Text 2。我可以编译但不能上传。错误 "The system cannot find the file specified"

python - 如何将字符串转换为函数的参数?

java - 如何组织辅助函数