21xrx.com
2025-04-23 22:49:11 Wednesday
文章检索 我的文章 写文章
如何获取C语言字符串的长度
2023-06-16 12:21:17 深夜i     10     0
C语言 字符串长度 strlen()

在C语言中,字符串是以\0结尾的字符数组。因此,要计算字符串的长度,只需迭代访问字符,直到遇到\0字符为止。

一个简单的方法是使用C标准库中的strlen()函数。它接受一个字符指针作为参数,并返回该字符串的长度,不包括\0字符。

以下是使用strlen()函数计算字符串长度的示例代码:

#include 
#include 
int main() {
  char str[] = "hello, world!";
  int len = strlen(str);
  printf("The length of the string is %d.\n", len);
  return 0;
}

如果你不想使用标准库中的函数,也可以手动实现计算字符串长度的算法。

以下是一种使用循环迭代计算字符串长度的示例代码:

#include 
int main() {
  char str[] = "hello, world!";
  int len = 0;
  while (str[len] != '\0') {
    len++;
  }
  printf("The length of the string is %d.\n", len);
  return 0;
}

通过以上两种方法,你可以很容易地获取指定字符串的长度。

  
  

评论区