C Language String length calculation is often used in programming, but also a job search must test.
The C language itself does not limit the length of the string, so the program must scan through the entire string to determine the length of the string.
In a program, it is common to use the strlen () function or sizeof to get the length of a string, but the length of the string obtained by these 2 methods is actually different, and we test it with the following function:
1#include <stdlib.h>2#include <string.h>3#include <stdio.h>4 intMain () {5 6 Chars1[ -] ="Hello World"; 7 Chars2[ -] = {'h','e','L','L','0',' ','W','o','R','L','D',' /'}; 8 CharS3[] ="hello\0 World"; 9 CharS4[] = {'h','e','L','L','0',' /',' ','W','o','R','L','D',' /'}; Ten Oneprintf"%d\t%d\t%d\t%d\n", strlen (S1), strlen (S2), strlen (S3), strlen (S4)); Aprintf"%d\t%d\t%d\t%d\n",sizeof(S1),sizeof(S2),sizeof(S3),sizeof(S4)); -}
Note that the function defines 4 strings, the basic data is "Hello World", but it should be noted that the string S1 and S2 given the size of the string array is 20, and then use 2 ways to assign the value; strings S3 and S4 are strings of S1 and S2 comparisons, The difference is that the S3 and the S4 string are inserted in the middle of a ' s '. The result of the function operation is as follows:
As can be seen from the running results, the strlen () function and the sizeof string length need to pay attention to the following points:
1. The string length evaluated by the strlen function is the number of elements from the first element of the string to the first ' + ' (if there is ' s ' in the middle of the string, the result is not the length of the entire string) and does not include the '
2. The result of sizeof is that the variable that stores the string takes up the amount of space that is used, and therefore will certainly include ' s '. If there is space after ' ", it will also be included in the result.
Explanation (related to the implementation principle of 2 evaluation methods):
1. One of the implementations of strlen () is to iterate over the string and terminate it when it encounters ' s ', so the result is the number of the first character element
2. SizeOf often uses the size of a variable to take up memory space, so it returns the amount of memory space occupied by the variable that stores the string, which is used to find the length of the string and is only feasible in certain cases, where the character array is filled with exactly one string.
Transferred from: http://blog.csdn.net/kstrwind/article/details/8036555
C Language String length (RPM)