gpt4 book ai didi

c - 非空终止 char* 数组的长度

转载 作者:行者123 更新时间:2023-11-30 21:42:49 26 4
gpt4 key购买 nike

下面的方法slength给了我一个无限循环(无限的“hello”语句)。要查找非空终止字符串的长度,由于没有 '\0',我需要注意什么?

int slength(const char *s) {
printf("hello");
int i = 0;
while (s != NULL) {
i++;
s++;
printf("hello");
}
return i;
}

这个方法似乎可行,但我觉得要考虑的检查太多了。有没有更简单的方法?

int silength(const char *s) {
int i = 0;
while( (*s>='a'&& *s<='z') || (*s>='A' && *s<='Z') || *s == ' ') {
i++;
s++;
printf("hello\n");
}
return i;
}

最佳答案

由于您没有使用标准 C 字符串,而是想要创建自己类型的字符串,因此您无法使用常见的 C 方法来循环字符串。我建议你制作一个像

这样的数据结构
struct string {
const char *text;
int length;
};

记录字符串的长度。使用附加长度信息进行循环。您可能必须创建自己的许多处理字符串的 C 标准库函数的版本,并且转换和工厂函数会很有用。

以下是 C 语言中跟踪长度的字符串实现的几个示例:

bstring作者:谢保罗

Text来自 D. R. Hanson 的 C 接口(interface)和实现

否则,只需使用以 null 结尾的字符串,因为这是 C 中的默认设置。例如,字符串文字以 null 字符结尾。

关于c - 非空终止 char* 数组的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31216604/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com