strlen函数演示代码
时间: 2023-10-28 18:02:07 浏览: 50
下面是一个简单的演示代码,演示如何使用C语言标准库中的strlen函数来计算字符串的长度:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
int len = strlen(str);
printf("Length of string '%s' is %d\n", str, len);
return 0;
}
```
这个程序首先包含了`stdio.h`和`string.h`头文件,分别用于输入输出和字符串操作。然后定义了一个字符串`str`,并使用`strlen`函数计算它的长度,并将结果存储在变量`len`中。最后,程序使用`printf`函数输出字符串的长度。运行该程序将输出:
```
Length of string 'Hello, world!' is 13
```
这表明这个字符串的长度为13个字符。
相关问题
strcspn和strlen函数
strcspn和strlen函数是C语言中的字符串处理函数,下面是它们的介绍和演示:
1. strlen函数
函数介绍:strlen函数用于计算字符串的长度,即字符串中字符的个数,不包括字符串末尾的空字符'\0'。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
int len = strlen(str);
printf("The length of the string is: %d\n", len); // 输出:The length of the string is: 11
return 0;
}
```
2. strcspn函数
函数介绍:strcspn函数用于计算字符串str1中第一个不包含字符串str2中任何字符的位置,返回值为该位置的下标。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello world";
char str2[] = "aeiou";
int index = strcspn(str1, str2);
printf("The index of the first character that does not appear in str2 is: %d\n", index); // 输出:The index of the first character that does not appear in str2 is: 1
return 0;
}
```
调用strlen函数求字符串长度
可以使用strlen函数来计算一个字符串的长度,该函数需要传入一个字符串的指针作为参数,返回字符串的长度(不包括字符串末尾的空字符)。
例如,以下代码演示了如何使用strlen函数计算字符串长度:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int len = strlen(str);
printf("Length of string '%s' is %d\n", str, len);
return 0;
}
```
输出结果为:
```
Length of string 'Hello, World!' is 13
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)