在 C 语言中,通过以下方法可获取字符串长度:使用 strlen() 函数,可直接返回字符串长度,不包括空字符;手动遍历字符串,逐个字符读取直到遇到空字符,可统计长度;对于字符数组,使用 sizeof() 运算符并减去 1,可获得排除空字符后的字符串长度。

如何获取 C 语言字符串长度
在 C 语言中,字符串是以空字符('\0')结尾的一串字符。为了获取字符串的长度,我们可以使用以下方法:
1. 使用 strlen() 函数:
<code class="c">int strlen(const char *str);</code>
示例:
立即学习“C语言免费学习笔记(深入)”;
<code class="c">#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
int length = strlen(str);
printf("字符串长度:%d\n", length);
return 0;
}</code>输出:
<code>字符串长度:13</code>
2. 手动遍历字符串:
<code class="c">int strlen(const char *str) {
int i;
while (str[i] != '\0') {
i++;
}
return i;
}</code>3. 使用 sizeof() 运算符(仅适用于字符数组):
<code class="c">int strlen(char str[]) {
return sizeof(str) - 1;
}</code>比较:
以上就是c语言中怎么获取字符串长度的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号