C 语言的 strlen 函数是什么?
C 库函数 size_t strlen(const char *str) 计算字符串 str 到(但不包括)终止空字符的长度。
一组字符称为字符串。
声明
下面是对数组的声明 -
char stringname [size];
例如 - char a[50];长度为 50 个字符的字符串
初始化
- 使用单个字符常量 -
char a[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}- 使用字符串常量 -
char a[10] = "Hello":;
访问 - 有一个控制字符串 "%s",用于访问字符串直到遇到 '\0'
strlen() 函数
此函数给出字符串的长度,即字符串中的字符数。
语法
strlen() 函数的语法如下 -
int strlen (string name)
示例程序
以下程序显示了 strlen() 函数的用法。
#include <string.h>
main ( ){
char a[30] = "Hello";
int l;
l = strlen (a);
printf ("length of the string = %d", l);
getch ( );
}输出
执行以上程序后,它会产生以下结果 -
length of the string = 5 Note : "\0" not counted as a character.
考虑另一个示例。
示例
以下是查找字符串长度的 C 程序 -
#include<stdio.h>
#include<string.h>
int main(){
int str1, str2;
//initializing the strings
char string1[] = "Welcome To";
char string2[] = {'T','U','T','O','R','I','A','L','\0'};
//calculating the length of the two strings
str1 = strlen(string1);
str2 = strlen(string2);
printf("string1 length is: %d
", str1);
printf("string2 length is: %d
", str2);
}输出
执行以上程序后,它会产生以下结果 -
string1 length is: 10 string2 length is: 8
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP