获取字符串的长度(以C++为单位)

Getting the length of a string in C++

本文关键字:C++ 为单位 字符串 获取      更新时间:2023-10-16
int strStr(string haystack, string needle) {
    int i, j;
    for(i = 0; i <= haystack.length() - needle.length(); i++){
        for(j = 0; j < needle.length(); j++){
            if(haystack[i+j] != needle[j]){
                break;
            }
        }
        if(j == needle.length()){
            return i;
        }
    }
    return -1;
}

这是我为实现 strStr 函数而编写的代码。我发现很奇怪,当 haystack = " 和 needle = "a" 时,它返回的结果是 32 而不是 -1。

但是,当我将第三行修改为

int k = haystack.length() - needle.length();
for(i = 0; i <= k; i++){

它返回正确的输出 -1。现在我真的很困惑。为什么我最初编写的代码是错误的?它们之间有什么区别?

使用:

int(haystack.length()) - int(needle.length())

请注意

cout<<(size_t(0)-size_t(1))<<endl;

显示

18446744073709551615