[C Language Study Notes---String Functions]

C language string functions

Preface:
Through the advanced knowledge of C language pointers, what practical functions should I continue to learn about C language?

/ Knowledge point summary /
Classification of string functions :
1. Find the length of a string: strlen
2. String functions with unlimited length: strcpy, strcat, strcmp
3. String functions with limited length: strncpy, strncat, strncmp
4 .String search function: strstr, strtok
5. Error message reporting function: strerroe, perror
6. Character classification function:
iscntrl – any control character
isspace – blank character: 'space', form feed '\f', carriage return '\ n', tab character '\t'.
isdigit — decimal digits 0~9
isxdigit — hexadecimal digits, including decimal digits, lowercase letters a f, uppercase letters A F
islower — lowercase letters a~z
isupper — uppercase letters A~Z
isalpha – letters a z or A Z
isalnum – letters or numbers, a z, A Z, 0~9
ispunct – punctuation marks, any graphic characters that are not numbers or letters
isgraph – any graphic characters
7. Character conversion function :
int tolower (int c); — Convert uppercase letters to lowercase letters
int toupper (int c); — Convert lowercase letters to uppercase letters
(here, the functions from 1 to 6 are summarized into string functions for explanation)

1. String function

1.1. strlen function

Library function : A library function used to find the length of a string. Essentially, it counts the number of characters before '\0' in the string.
Prototype : size_t strlen( const char *string);
Header file : #include <string.h >

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	size_t len1 = strlen("abcdef");
	//等价,其中传参传递的首元素地址
	const char* str = "abcdef";
	size_t len2 = strlen(str);
	
	printf("%d\n", len1);//6
	printf("%d\n", len2);//6

	//另外得注意,字符串本身就放置了'\0'的情况
	size_t len1 = strlen("abc\0def");
	const char* str = "abc\0def";
	size_t len2 = strlen(str);

	printf("%d\n", len1);//3
	printf("%d\n", len2);//3
	return 0;
}

Supplementary features of size_t:

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	if (strlen("abc") - strlen("abcdef") > 0)//因为strlen的返回值是无符号数
		//两个无符号数相减得到的依然是无符号数
		//相等于即使相减为负数,但是返回值会约束其符号位无效了,从而成为一个很大的数远远大于0
		printf(">=0\n");
	else
		printf("<=0\n");
	return 0;
}

1.2. strcpy function

Function : Complete the copy of the string and copy the original target string address to the target string address.
Prototype : char *strcpy( char *strDestination, const char *strSource );
Header file : #include <string.h>

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	char arr1[20] = {
    
     0 };
	char arr2[] = "hello";
	strcpy(arr1, arr2);
	printf("%s\n", arr1);
	return 0;
}

Several notes on using strcpy :
1. The source string must end with '\0' (because '\0' will be included in the copy)
2. '\0' in the source string will be copied to the target space
3. The target space must be large enough to ensure that the source string can be stored.
4. The target space must be variable (cannot be a constant)
. 5. Learn to simulate implementation to gain better control.

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	char arr1[20] = "xxxxxxxxxxxxxxx";
	//char arr2[] = "hello";
	//char arr2[] = {'A','B','C'};
	char arr2[] = {
    
     'A','B','C','\0'};
	strcpy(arr1, arr2);
	printf("%s\n", arr1);
	return 0;
}

Summary: So it is up to the programmer to decide that the target space must be large enough, and the target space must have writable permissions

1.3. strcat function

Function : Append the source string address to the target string address
Prototype : char *strcat( char *strDestination, const char *strSource );
Header file : <string.h>
Execution steps :
1. Find the end of arr1'\ 0'
2. Append the content of arr1 to the end of arr1 (the first address of arr2 will be overwritten, and the '\0' of arr1 will be appended)

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char arr1[20] = "abc";
	char arr2[] = "def";
	strcat(arr1, arr2);
	printf("%s\n", arr1);//abc(追加)def
	return 0;
}

Notes :
1. The target space is large enough
2. The target space must have '\0' (to ensure that the end of the target space can be found)
3. The source string must also have '\0', which will be copied in one pass during copying to form The new string has the end bit identifier
4. When appending itself, the source pointer and the target pointer both point to the first character, and then the '\0' of the source string will be overwritten, resulting in the '\' not being found when appending later. 0'. Although the library function can be implemented, it is not recommended

1.4. strcmp function

Function : Compare the size of strings (not comparing the length, but comparing the character size at the corresponding position, that is, the ASCII code value)
Prototype : int strcmp( const char *string1, const char *string2);
Header file : <string.h>
Return Value :
Value Relationship of string1 to string2
//< 0 string1 less than string2
//0 string1 identical to string2
//> 0 string1 greater than string2
The standard stipulates : Compare ASCLL code value
1. The first string is greater than the second String, returns a number greater than 0
2. If the first string is equal to the second string, returns 0
3. If the first string is less than the second string, returns a number less than 0

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char arr1[] = "abcdef";
	char arr2[] = "abq";
	int ret = strcmp(arr1, arr2);
	printf("%d\n", ret);//-1,第一个字符串比第二个字符串小,返回小于零的数值
	return 0;
}

Summary :
strlen, strcat, strcmp, strcpy are string functions with unlimited length;
then introduce the string functions with limited length: strncat, strncmp, strncpy

1.5. strncpy function

Function : String copy (length can be specified)
Prototype : char* strncpy(char* strDest, const char* strSource, size_t count);
Header file : <string.h>

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char arr1[20] = {
    
     0 };
	char arr2[] = "abcdefghi";
	strncpy(arr1, arr2, 3);
	printf("%s\n", arr1);//abc
	char arr1[20] = "xxxxxxxxxxxxxxx";
	char arr2[] = "abcdefghi";
	strncpy(arr1, arr2, 3);
	printf("%s\n", arr1);//abcxxxxxxxxxx
	return 0;
}

Explore the impact of copy length :

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	char arr1[20] = "xxxxxxxxxxxx";
	char arr2[] = "abc";
	strncpy(arr1, arr2, 6);//长度比str2长时,自动补的'\0'.
	printf("%s\n", arr1);//abc\0\0\0
	return 0;
}

1.6. strncat function

Function : String append (length can be specified)
Prototype : char* strncat(char* strDest, const char* strSource, size_t count);
Header file : <string.h>

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	char arr1[20] = "abc";
	char arr2[] = "defghi";
	strncat(arr1, arr2, 3);//长度比str2长时,自动补的'\0'.
	printf("%s\n", arr1);//abc
	return 0;
}

Explore the appending situation 1 of '\0':

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char arr1[20] = "abc\0xxxxxxxxxxx";//字符串中本身具备'\0'时,依然以'\0'开始覆盖,最后补'\0'结束
	char arr2[] = "defghi";
	strncat(arr1, arr2, 3);
	printf("%s\n", arr1);//abcdef\0
	return 0;
}

Explore the append situation 2 of '\0':

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char arr1[20] = "abc\0xxxxxxxxxxx";//字符串中本身具备'\0'时,依然以'\0'开始覆盖,最后补'\0'结束
	char arr2[] = "defghi";
	strncat(arr1, arr2, 10);//10长度比str2长时,自动在末尾补'\0'.此函数就不会对超出长度的字符进行操作了
	printf("%s\n", arr1);//abcdef
	return 0;
}

1.7. strncmp function

Function : String size comparison (length can be specified)
Prototype : int strncmp( const char *string1, const char *string2, size_t count);
Header file : <string.h>

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char arr1[] = "abcdef";
	char arr2[] = "abcqw";
	//int ret = strncmp(arr1, arr2, 3);
	//printf("%d\n", ret);//0

	int ret = strncmp(arr1, arr2, 4);//比较字符串前4个字符
	printf("%d\n", ret);//-1
	return 0;
}

1.8. strstr function

Function : Find a string in a string (find a substring or segment in a string). strstr will return the position where str2 first appears in str1. If there is no str2 in str1, NULL will be returned. Prototype: const char
* strstr (const char *string, const char *strCharSet);
Header file : <string.h>

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	char arr1[] = "abcdefghi";
	char arr2[] = "def";
	char* ret = strstr(arr1, arr2);
	if (ret == NULL)
	{
    
    
		printf("找不到\n");
	}
	else
	{
    
    
		printf("%s\n", ret);//defghi
	}
	return 0;
}

1.9. strtok function

Function : Commonly used to cut strings
Prototype : char *strtok( char *strToken, const char *strDelimit);
Header file : <string.h>

Note :
The strtok function finds the next mark in str, ends it with '\0', and returns a pointer to this mark; the
strtok function will change the string being operated on, so when using the strtok function to split the string It is generally a temporary copy of the content and can be modified.
For example :
IP address: It is originally an unsigned integer. This kind of integer is not convenient to remember, so this integer is converted into dotted decimal representation
[email protected] - the separator can be @ or ' . '
192.168.101.23 – The delimiter can be ' . '

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	char arr[] = "[email protected]";
	char* p = "@.";
	char* s = strtok(arr, p);//将被标记的地方改为'\0',再把'\0'之前的切分出来。
	printf("%s\n", s);
	return 0;
}

Summary: The strings split using the strtok function are generally temporarily copied and can be modified.
As shown below, a new array is used to save the original array data:

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	char arr[] = "[email protected]";
	char buf[200] = {
    
     0 };
	strcpy(buf, arr);

	char* p = "@.";
	char* s = strtok(buf, p);//将被标记的地方改为'\0',再把'\0'之前的切分出来。
	printf("%s\n", s);

	return 0;
}

Summary :
The first parameter of the strtok function is NULL. The function will start at the saved position in the same string and find the next mark.
If no more tokens exist in the string, a NULL pointer is returned.

As shown below, each call will save the mark of the last call (with memory function), and so on:

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	char arr[] = "[email protected]";
	char buf[200] = {
    
     0 };
	strcpy(buf, arr);

	char* p = "@.";
	char* s = strtok(buf, p);//将被标记的地方改为'\0',再把'\0'之前的切分出来。
	printf("%s\n", s);

	s = strtok(NULL, p);
	printf("%s\n", s);

	s = strtok(NULL, p);
	printf("%s\n", s);
	return 0;
}

For the practicality of the code, tags are identified sequentially in a loop and the code is optimized :

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	char arr[] = "[email protected]";
	char buf[200] = {
    
     0 };
	strcpy(buf, arr);

	char arr2[] = "192.168.101.23";
	char buf2[200] = {
    
     0 };
	strcpy(buf2, arr2);

	char* p = "@.";
	char* s = NULL;
	for (s = strtok(buf, p); s != NULL; s = strtok(NULL, p))
	{
    
    
		printf("%s\n", s);
	}

	char* p2 = ".";
	for (s = strtok(buf2, p2); s != NULL; s = strtok(NULL, p2))
	{
    
    
		printf("%s\n", s);
	}
	return 0;
}

Summary :
1. The strtok function finds the next mark in str, ends it with \0, and returns a pointer to this mark.
2. The first parameter of the strtok function is not NULL, the function will find the first mark in str, and the strtok function will save its position in the string. 3. The
first parameter of the strtok function is NULL, and the function will Starting at the position in a string that will be saved, the next token is looked for.
4. If there are no more tags in the string, return the tag as a NULL pointer

1.10. strerror function

Function : Translate error codes into error messages and return the starting address of the string of error messages.
Prototype : char *strerror(int errnum);
Header file : <string.h>

Error codes such as common web pages that cannot be opened are displayed: -404-
When using library functions in C language, if an error occurs, the error code will be placed in the errno variable. errno is a global variable and can be used directly.

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		printf("%d: %s\n", i, strerror(i));
	}
	return 0;
}

The strerror function is often used to determine file operations.
An example of opening a file is shown:
fopen opens the file in the form of reading. If the file exists, the opening is successful; if the file does not exist, the opening fails.

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	FILE* pf = fopen("add.txt", "r");
	if (pf == NULL)
	{
    
    
		printf("打开文件失败,原因是:%s\n",strerror(errno));
		return 1;
	}
	else
	{
    
    
		printf("打开文件成功\n");
	}
	return 0;
}

Compare the perroe function :
Prototype : void perror( const char *string);
Function : Directly print the error code, the corresponding error message (first print the custom information: xxx, and then directly print the error reason)
Equivalent : perror == printf + strerror

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	FILE* pf = fopen("add.txt", "r");
	if (pf == NULL)
	{
    
    
		perror("打开文件失败");
		return 1;
	}
	else
	{
    
    
		printf("打开文件成功\n");
	}
	return 0;
}

2. Character classification function

Character classification function:
iscntrl - any control character
isspace - whitespace character: 'space', form feed '\f', carriage return '\n', tab character '\t'...
More commonly used:
isdigit - decimal digits 0~9
isxdigit – Hexadecimal digits, including decimal digits, lowercase letters a f, uppercase letters A F
islower – lowercase letters a~z
isupper – uppercase letters A~Z
isalpha – letters a z or A Z
isalnum – letters or numbers, a z,A Z,0~9
ispunct – punctuation mark, any graphic character that is not a number or letter
isgraph – any graphic character

Here are common examples

2.1. islower function

Prototype : int iswlower(wint_t c);
Header file : <ctype.h>
Function : Determine whether the character is lowercase letter, if it is lowercase, return a non-zero value; if not, return 0

#include <stdio.h>
#include <ctype.h>

int main()
{
    
    
	char ch = 'a';
	if (islower(ch))
	{
    
    
		printf("是小写\n");
	}
	else
	{
    
    
		printf("不是小写\n");
	}
	return 0;
}

2.2. isdigit and isxdight functions

Prototype : int isdigit( int c );
Header file : <ctype.h>
Function : Determine whether the character is a decimal number 0~9

Prototype : int isxdigit( int c );
Header file : <ctype.h>
Function : Determine whether the character is a hexadecimal number, including decimal numbers, lowercase letters a f, uppercase letters A F

#include <stdio.h>
#include <ctype.h>
int main()
{
    
    
	//if(ch >= 'a' && ch <= 'z')
	int ret = islower('a');
	printf("%d\n", ret);

	int ret2 = isdigit('5');
	printf("%d\n", ret2);

	int ret3 = isxdigit('c');
	printf("%d\n", ret3);
	return 0;
}

2.3. islower and isupper functions

Prototype : int islower( int c );
Header file : <ctype.h>
Function : Determine whether the character is a lowercase letter a~z

Prototype : int isupper( int c );
Header file : <ctype.h>
Function : Determine whether the character is an uppercase letter A~Z

#include <stdio.h>
#include <ctype.h>

int main()
{
    
    
	char ch1 = 'A';
	char ch2 = 'a';
	if(islower(ch2))
		printf("小写字母:%c\n",ch2);
	if(islower(ch1))
		printf("大写字母:%c\n",ch1);
	return 0;
}

3. Character conversion function

C language has only two character conversion functions: tolower and toupper

3.1. tolower function

Prototype : int tolower( int c );
Header file : <ctype.h>
Function : Convert uppercase letters to lowercase letters

#include <stdio.h>
#include <ctype.h>

int main()
{
    
    
	char arr[] = "TEST String.";
	char* p = arr;
	while (*p)
	{
    
    
		if (isupper(*p))
		{
    
    
			*p = tolower(*p);
		}
		p++;
	}
	printf("%s\n", arr);
	return 0;
}

3.2. toupper function

Prototype : int toupper( int c );
Header file : <ctype.h>
Function : Convert lowercase letters to uppercase letters

#include <stdio.h>
#include <ctype.h>

int main()
{
    
    
	int ret = tolower('A');
	printf("%c\n", ret);//a

	int ret2 = toupper('a');
	printf("%c\n", ret2);//A

	int ret3 = tolower('A');
	printf("%c\n", ret3);//a
	ret3 = toupper(ret3);
	printf("%c\n", ret3);//A
	return 0;
}

4. Conclusion

Familiarity with the use of each function is beneficial to the readability and efficiency of the program. Please correct me if there are any errors in this note.
Half an acre of sugar cubes are opened, and the skylight and cloud shadows linger together.
Ask where the canal can be so clear? Because there is a source of living water. -Zhu Xi (feelings after reading the book)

Guess you like

Origin blog.csdn.net/m0_69455439/article/details/133209161