Get the length of string and character array

The commonly used functions in C/C++ to obtain the length of a string or the length of a string array are
sizeof()
length()
strlen()
size(), of

which strlen(str) and str.length() and str.size() can be used Used to find the length of the string.
str.length() and str.size() are member functions used to find string objects.
strlen(str) is used to find the length of a string array. The parameter is char*.
Discrimination of the difference between strlen() and sizeof()

The strlen(char*)
function finds the actual length of the string, it can be used to obtain the length of the dynamic actual character array, from the beginning to the first "\0" encountered, if only the definition does not give an initial value, this result It is uncertain, it will search from the first address of the array until it encounters "\0" to stop searching.

sizeof()
asks for the number of bytes in the total space, static, it is related to the size of the initial state character array, the size is equal to the size of the initial character array or equal to the size of the initial character array + 1
in C++, if defined If it is a string array, then if you want to get the length of the array, you can only use sizeof (array name), not strlen (str).

char str[20]="0123456789"; 
int   a=strlen(str); a=10;strlen 计算字符串的长度,以\0'为字符串结束标记。 
int   b=sizeof(str); b=20;sizeof 计算的则是分配的数组str[20] 所占的内存空间的大小,不受里面存储的内容影响

char *str1="absde";
char str2[]="absde";
char str3[8]={
    
    'a',};
char ss[] = "0123456789";
输出:
sizeof(str1)=4;
sizeof(str2)=6;
sizeof(str3)=8;
sizeof(ss)=11

Guess you like

Origin blog.csdn.net/weixin_43902941/article/details/105974496