C++用指针算法查找字符串长度

C++ Finding String Length With Pointer Arithmetic

本文关键字:字符串 查找 算法 指针 C++      更新时间:2023-10-16

我现在正在学习Comp Sci课程,我的老师在黑板上写的一个例子如下-概念是创建一个string长度函数,该函数使用指针算术返回具有字符串长度的size_t。我理解这个概念,但每次我尝试这个例子时,我的结果都是0

using namespace std;
size_t strlen(const char* str);
int main(int argc, char** argv) {
    char test[] = {'h','e','l','l','o',''};
    cout << strlen(test);
    return 0;
}
size_t strlen(const char* str){
    int idx = 0;
    for( ; *str; str++, idx++){
        return(idx);
    }
}

如果有人能深入了解出了什么问题,我将不胜感激。

谢谢!:(

for( ; *str; str++, idx++){
    return(idx);
}

将在第一次迭代时返回idx。您需要做的是让for循环运行,然后返回idx。这看起来像:

for( ; *str; str++, idx++){}
return(idx);

你可以用;来结束for语句,但我发现这很容易被忽略

这个版本实际上使用了指针算术:

size_t strlen(const char* str)
{
    const char * const os = str;
    while ( *str ) ++str;
    return str - os;
}

如@IgorTandetnik所示,循环在1次迭代后终止

size_t strlen(const char* str){
    size_t idx = 0;
    for( ; *str; str++, idx++){
        return(idx); // <------ here
    }
}

Clang实际上通过-Weverything警告级别捕捉到了这一点

> main.cpp:15:18: warning: loop will run at most once (loop increment
> never executed) [-Wunreachable-code-loop-increment]
>     for( ; *str; str++, idx++){
>                  ^~~~~~~~~~~~

修复很简单:

size_t strlen(const char* str){
    size_t idx = 0;
    for( ; *str; str++, idx++) {} // here       
    return(idx);    
}

实时示例

size_t strlen(const char* str){
    int idx = 0;
    while(*str++)
        idx++;
    return idx; 
}

试试上面的,看看你们是否得到了合适的字符串长度。