C语言求字符串长度的方法有哪些
- 使用strlen函数:可以通过调用标准库函数strlen来获取字符串的长度。例如:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int len = strlen(str);
printf("Length of the string: %d\n", len);
return 0;
}
- 遍历字符串:可以通过遍历字符串的每个字符,直到遇到字符串结束符’\0’来计算字符串的长度。例如:
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
int len = 0;
while (str[len] != '\0') {
len++;
}
printf("Length of the string: %d\n", len);
return 0;
}
- 自己实现一个计算字符串长度的函数:可以自己实现一个函数来计算字符串的长度。例如:
#include <stdio.h>
int strLength(char *str) {
int len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}
int main() {
char str[] = "Hello, World!";
int len = strLength(str);
printf("Length of the string: %d\n", len);
return 0;
}