C++用指针算法查找字符串长度
C++ Finding String Length With Pointer Arithmetic
我现在正在学习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;
}
试试上面的,看看你们是否得到了合适的字符串长度。
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 按类型与字符串查找对象
- 使用C RTTI(内置)通过字符串查找功能指针
- 关于获取行和字符串查找函数的问题
- 字符串查找方法找不到第一字母
- C++ 字符串.查找()
- 遇到字符串::查找的问题
- 将一个数组作为子字符串查找到另一个数组中
- 字符串查找第一个非的 C++ 问题
- 如何将通配符与字符串::查找一起使用
- 字符串::查找问题 (C++)
- 性能标准::strstr vs. 标准::字符串::查找
- C++字符串::查找崩溃应用程序
- 使用字符串查找单词的正确方法是什么
- 如何在<string>没有 std::string 中介的情况下制作一个支持通过 C 字符串查找的集合?
- 使用C++根据行中的第一个字符串查找行(仅一个)
- Borland字符串::查找bug
- std::map如何通过字符串查找元素
- 字符串查找函数返回奇数
- 如何使用子字符串查找数字行的正确部分