通过指针增量遍历C字符串
Traversal of C string through pointer incrementation
我正在阅读Bjarne Stroustrup的C++之旅,我很难理解早期的例子。在下面的代码中,while循环用于在C风格字符串上增加指针,直到指针碰到null字符。我不明白为什么指向null字符会导致指针采用nullptr的值。它似乎应该是一个非常好的指针,恰好指向一个null值。如果这是作者的错误,我会感到惊讶,因为这本书包含在stackexchange的推荐中:最终C++图书指南和列表
int count_x(char∗ p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
if (p==nullptr) return 0;
int count = 0;
for (; p!=nullptr; ++p)
if (∗p==x)
++count;
return count;
}
要检查空字符,应该测试*p != ' '
,而不是p != nullptr
。
由于您提到的原因,它会分段。尝试:
for (; *p; ++p)
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 广义后缀树遍历以查找最长的公共子字符串
- 在遍历字符串时,为什么我没有超出范围错误,即使我已经超出了它的长度?
- 如何遍历特定字符串的向量
- 在C 中的字符串向量的字符串元素中循环遍历所有字符
- 是否可以遍历文本文件行并使用字符串流来解析每一行
- 在字符串数组中遍历每个字符
- 如何遍历整个字符串并一次播放一个字符C++
- 通过指针循环遍历字符串数组
- 如何遍历字符串中的所有utf-8代码点
- 在C++中遍历字符串
- 通过指针增量遍历C字符串
- 无法使用迭代器遍历字符串:但是我的带有索引的版本确实有效
- 如何使用find()遍历字符串
- 遍历C++中的字符串列表,出了什么问题?
- 如何遍历 std::vector<char> 并查找以 null 结尾的 c 字符串
- c++遍历字符串
- 逐个字符遍历字符串字符