C语言和C++编程语言提供 strlen()
函数以计算或返回给定字符串或字符数组的大小。字符串和字符数组是C和C++中的简单数据类型,这是字符数组。提供的strlen()函数 string.h
标题或库。
null
strlen()函数语法
strlen()函数具有以下语法,其中我们提供char数组或字符串作为参数。
size_t strlen(const char *STR)
-
size_t
strlen()函数的返回值类型,通常为整数或long,返回给定字符串或字符数组的大小或长度。 -
const char *STR
指定要获取长度或大小的字符串或字符数组。
字符串的字符串长度
我们将从计算给定字符串的长度开始。实际上,我们将提供一个char数组,它将以字符串格式显示。我们将为名为a和b的字符串提供值 My name is poftut.com
和 I love poftut.com
. 我们将用 strlen()
功能。
#include#include int main(){ char a[100]="My name is poftut.com"; char b[100]="I love poftut.com"; a_length = strlen(a); b_length = strlen(b); printf("Length of string a = %ld ",a_length); printf("Length of string b = %ld ",b_length); return 0;}
具有Char指针的字符串的字符串长度
或者,我们可以使用char指针来创建字符串,它实际上也是一个char数组或字符串。我们将为名为a和b的字符串提供值 My name is poftut.com
和 I love poftut.com
. 我们将用 strlen()
功能。
#include#include int main(){ char a[100]="My name is poftut.com"; char b[100]="I love poftut.com"; printf("Length of string a = %ld ",strlen(a)); printf("Length of string b = %ld ",strlen(b)); return 0;}
字符数组的字符串长度
或者,我们可以逐项创建或定义一个char数组,然后计算整个char数组的大小。我们将设置 Hello poftut.com
将一个字符一个字符一个字符地转换成一个字符数组。
#include#include int main(){ char a[100]={'H','e','l','l','o',' ','p','o','f','t','u','t','.','c','o','m'}; printf("Length of string a = %ld ",strlen(a)); return 0;}
输入字符串或字符数组的长度
我们还可以使用 scanf()
. 我们将从标准输入或控制台读取输入并设置为char数组,然后使用strlen()函数计算长度。
#include#include int main(){ char name[100]; char sentence[100]; printf("Please enter your name"); scanf("%s",name); printf("Please enter a sentence"); scanf("%s",sentence); printf(""); printf("Length of name = %ld ",strlen(name)); printf("Length of sentence = %ld ",strlen(sentence)); return 0;}

相关文章: 如何将Python字符串转换为List?
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END