C language-detailed explanation of character functions and string functions


Detailed introductions to the following character functions and string functions can be found on this website:https://legacy.cplusplus.com/

1. Character classification function

Function: Used to determine what type of character a character belongs to
Header file:#include<ctype.h>
Enumeration:
Insert image description here

We use an islower function here to determine whether a character is lowercase.

int islower ( int c );

islower can determine whether c in the parameter part is lowercase.
Use the return value to indicate whether it is a lowercase character. If it is a lowercase character, it will return a non-0 integer. If it is not a lowercase character, it will return 0.

Code:

#include<ctype.h>
#include<stdlib.h>
int main() {
    
    
	char a = getchar();
	if (islower(a))
		printf("小写");
	else
		printf("其他");
	return 0;
}

Run result:
Insert image description here
Other similar judgments are also made in this way

2. Character conversion function

There are also functions for exchanging lowercase letters with uppercase characters, such as:

int tolower ( int c ); //将参数传进去的⼤写字⺟转⼩写 
int toupper ( int c ); //将参数传进去的⼩写字⺟转⼤写

Let’s try it:

#include<ctype.h>
#include<stdlib.h>
int main() {
    
    
	char a = getchar();
	if (islower(a)) {
    
    
		char b = toupper(a);
		printf("%c\n", b);
	}
	else
		printf("输入的不是小写字母");
	return 0;
}

operation result:
Insert image description here

3. Usage and simulation implementation of strlen

Parameters and return types:

 size_t strlen ( const char * str );

1. The string uses ‘\0’ as the end mark, and the strlen function returns the number of characters that appear before ‘\0’ in the string (excluding ‘\0’).
2. The string pointed to by the parameter must end with ‘\0’.
3. Note that the return value of the function is size_t, which is unsigned (error-prone).
4. The use of strlen requires the header file (string.h).

use:

#include<string.h>//包含头文件
int main() {
    
    
	char* a = "abcdef";
	size_t  te = strlen(a);//计算字符串中‘\0之前的元素个数,注意返回类型为size_t
	printf("%zd\n", te);//打印
	return 0;
}

operation result:
Insert image description here

Simulate strlen function

1. We create a function whose parameters are used to receive the first address of the string. The return type is size_t, the same as strlen.
2. We set a counter to count the number of characters. Traverse the string through a loop, and the counter increases ++ each time it is traversed, until it encounters '\0'

Code:

size_t mn_strlen1(const char* s) {
    
    
	//我们不希望改变字符串 所以用const修饰,s用来接收首地址
	int i = 0;//计数器
	assert(s);
	while (*s) {
    
    //当*s为'\0'时打破循环
		i++;
		s++;//字符地址++
	}
	return i;//返回
}
int main() {
    
    
	char a[] = "abcdef";
	size_t len1 = mn_strlen1(a);
	printf("%zd\n", len1);
	return 0;
}

operation result:
Insert image description here

4. Use and simulation implementation of strcpy

Parameters and return types:

 char* strcpy(char * destination, const char * source );

1. The source string must end with ‘\0’.
2. The ‘\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 modifiable.

use:

#include<string.h>//包含头文件
int main() {
    
    
	char a[20] = {
    
     0 };//目标空间一定要够大
	char b[] = "abcdef";//字符串的‘\0'也会拷贝
	char* p = strcpy(a, b);//用p来接收返回来的地址
	printf("%s\n", p);//打印
	return 0;
}

Run result:
Insert image description here
Simulate strcpy function
1. We create a function whose parameters are the address of the target space and the source string address, and return is the first address of the target space
2. We can first create a pointer variable to remember the first address of the target space, and then transfer each character in the source string to the target space until Until '\0' is transferred, the first address of the target space is finally returned
Implementation code:

//strcpy模拟实现
char* mn_strcpy(char* p1, const char* p2) {
    
    
	//我们不希望改变字符串p2 所以用const修饰,p1为目标空间的首地址,p2为源字符串首地址
	assert(p1);//防止为NULL
	assert(p2);
	char* p = p1;//保存目标空间首地址
	while (*p1=*p2) {
    
    //解引用将*p2的字符赋给*p1
		p1++;//地址加加
		p2++;
	}
	return p;//返回目标空间首地址
 }
int main() {
    
    
	char a[20] = {
    
     0 };
	char b[] = "abcdef";
char*p=mn_strcpy(a, b);
	printf("%s\n", p);
	return 0;
}

operation result:

Insert image description here

5. Use of strncpy function

Parameters and return types:

`char * strncpy ( char * destination, const char * source, size_t num );

1. Copy num characters from the source string to the target space.
2. If the length of the source string is less than num, after copying the source string, append 0 to the end of the target until num.

use:

int main() {
    
    
	char a[20] = {
    
    0};
	char b[] = "abcde";
	printf("%s\n", strncpy(a, b,3));//只拷贝三个
	return 0;
}

operation result:
Insert image description here

6. Usage and simulation implementation of strcat

Parameters and return types:

char* strcat(char * destination, const char * source );

Function: Connect the source string to the target string
1. The source string must end with ‘\0’.
2. There must also be \0 in the target string, otherwise there is no way to know where to start appending.
3. The target space must be large enough to accommodate the content of the source string.
4. The target space must be modifiable.

use:

#include<string.h>//包含头文件
int main() {
    
    
	char a[20] = "qwe";//目标空间一定要够大
	char b[] = "abcdef";
	char* p = strcat(a, b);//用p来接收返回来的地址
	printf("%s\n", p);//打印
	return 0;
}

Run result:
Insert image description here
Simulate strcat function

1. We create a function whose parameters are the address of the target space and the source string address, and the return is the first address of the target space
2. We first create a pointer variable. Store the first address of the target space, and then use a loop to traverse the string in the target space until \0' is found, stop
3. Transfer every character in the source string to the target space. Until '\0' is transferred, the first address of the target space is returned

Implementation code:

//strcat模拟
char* nm_strcat(char* p1, const char* p2) {
    
    
	//我们不希望改变字符串p2 所以用const修饰,p1为目标空间的首地址,p2为源字符串首地址
	char* p = p1;//保存目标空间首地址
	assert(p1);
	assert(p2);
		while (*p1)//遍历*p直到找到‘/0’
			p1++;
		while (*p1=*p2) {
    
    ///解引用将*p2的字符赋给*p1
		p1++;
		p2++;
	}
	return p;//返回目标空间首地址
}
int main() {
    
    
	char a[20] ="grr";
	char b[] = "abcdef";
	char*p=nm_strcat(a, b);
	printf("%s\n", p);
	return 0;
}

operation result:
Insert image description here

7. Use of strncat function

Parameters and return types:

char * strncat ( char * destination, const char * source, size_t num );

1. Append the first num characters of the string pointed to by source to the end of the string pointed by destination, and then append a \0 character
2. If the string pointed by source When the length is less than num, only the content up to \0 in the string will be appended to the end of the string pointed to by destination

use:

int main() {
    
    
	char a[20] = "xxx";
	char b[] = "abcde";
	printf("%s\n", strncat(a, b,3));

	return 0;
}

operation result:
Insert image description here

8. Usage and simulation implementation of strcmp

Parameters and return types:

int  strcmp(comst char * destination, const char * source );

If the first string is greater than the second string, then a number greater than 0 is returned
If the first string is equal to the second string, then 0< /span> So how to judge two strings? Compare the ASCII code values ​​of characters at corresponding positions in two strings.
If the first string is smaller than the second string, a number smaller than 0 will be returned.

use:

#include<string.h>//包含头文件
int main() {
    
    
	char a[] = "abfa";//
	char b[] = "abqc";
	int t = strcmp(a, b);
		if (t == 0)
		printf("a=b");
	else if (t > 0)
		printf("a>b");
	else
		printf("a<b");
	return 0;
}

Comparison process chart:
Insert image description here
Running results:
Insert image description here
Simulate strcmp function

1. We create a function whose parameters receive the first addresses of the two strings respectively and return int data
2. Compare the two strings one by one through a loop until There is a situation where they are not equal or both are '\0'

Code:

int mn_strcmp(const char* p1, const char* p2) {
    
    
	//	我们不希望改变字符串p2 和p1所以用const修饰,p1为目标空间的首地址,p2为源字符串的首地址
	assert(p1);//防止为NULL
	assert(p2);
	while (*p1 == *p2) {
    
    //相等就继续比较
		if (*p1 == '\0')//当双方都是\0时就是两字符串相等
			return 0;
		p1++;
		p2++;
	}
	return *p1 - *p2;//p1>pp2时返回正值,否则反之
}
int main() {
    
    
	char* a = "ger";
	char* b = "ger";
	int t = mn_strcmp(a, b);
	if (t == 0)
		printf("a=b");
	else if (t > 0)
		printf("a>b");
	else
		printf("a<b");
	return 0;
}

operation result:
Insert image description here

9. Use of strncmp function

Parameters and return types:

 int strncmp ( const char * str1, const char * str2, size_t num );

Compare the first num characters of str1 and str2. If they are equal, continue to compare, up to num characters. If the difference is found in advance
, just Ending early, the larger character is in a string that is larger than the other one. If num characters are equal, it means equal and returns 0

use:

int main() {
    
    
	char* a = "gerqq";
	char* b = "gera";
	int t = strncmp(a, b,3);//比较前三个字符
	if (t == 0)
		printf("a=b");
	else if (t > 0)
		printf("a>b");
	else
		printf("a<b");
	return 0;
}

operation result:
Insert image description here

10. Usage and simulation implementation of strstr

Parameters and return types:

char * strstr ( const char * str1, const char * str2);

Function: Find str2 in str1
1. The function returns the position where the string str2 first appears in the string str1
2. Character The string comparison match does not contain the \0 character, and \0 is used as the end mark

use:

#include<string.h>//包含头文件
int main() {
    
    
	char a[] = "abcdfa";//
	char b[] = "cd";//
	char* p = strstr(a, b);//在a字符串中找b字符串,找到之后返回找到时在a的地址
	printf("%s\n", p);
	return 0;
}

Run result:
Insert image description here
Simulate strsstr function

1. We create a function, the parameters receive the first addresses of the two strings respectively, and return the address when the search is successful
2. The first case is that the searched string is NULL At this time, we directly return the target string. Secondly, we need to set three pointers. One of them records the position where the target string moves to, and the other two are traversed separately. If they find the same, they will continue. If they are different, they will jump out. After jumping out, they will be recorded. The pointer is ++, and then the next traversal is performed until the '\0' of the source string is found, which means the search is successful, otherwise it will not be found

Code:

char* mn_strstr(const  char* p1, const char* p2) {
    
    
	assert(p1);//	我们不希望改变字符串p2 和p1所以用const修饰,p1为目标空间的首地址,p2为源字符串的首地址
	if (!*p2)//源字符串为NILL时直接返回p1
		return p1;
	char* con = p1;//记录指针,从第一个位置开始
	char* s1 = NULL;//空
	char* s2 = NULL;//
	while (*con) {
    
    //当将目标字符串都找一次还没有就返回NULL
		s1 = con;//目标字符移动指针
		s2 = p2;//源字符移动指针
		while ((*s1 == *s2) && *s2) {
    
    //对比,当s2为'\0'时结束
			s1++;
			s2++;
		}
		if (*s2 == '\0')
			return con;
		con++;
	}
	return NULL;
}

int main() {
    
    
	char* a = "cdf";
	char* b = "cqf";
	char* p = mn_strstr(a, b);
	if (!p)
		printf("找不到\n");
	else
		printf("%s\n", p);
	return 0;
}

operation result:
Insert image description here

11. Use of strtok function

Parameters and return types:

char * strtok ( char * str, const char * sep);

1. The sep parameter points to a string, defining the set of characters used as delimiters
2. The first parameter specifies a string, which contains 0 Or multiple tokens separated by one or more delimiters in the sep string.
3. The strtok function finds the next tag in str, ends it with \0, and returns a pointer to this tag. (Note: The strtok function will change the manipulated string, so the string split using the strtok function is generally a temporary copy and can be modified.)
4.strtok If the first parameter of the function is not NULL, the function will find the first token in str, and the strtok function will save its position in the string.
5. The first parameter of the strtok function is NULL, and the function will search for the next mark starting from the saved position in the same string.
6. If there are no more tokens in the string, return a NULL pointer

use:

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char arr[] = "192.168.6.111";
	char* sep = ".";//作为分割符
	char* str = NULL;//等会作接收返回值
	for (str = strtok(arr, sep); str != NULL; str = strtok(NULL, sep))
	{
    
    
		printf("%s\n", str);
	}
	return 0;
}

operation result:
Insert image description here

12. Use of strerror function

Parameters and return types:

char * strerror ( int errnum );

The strerror function can return the string address of the error message corresponding to the error code in the parameter part. Some error codes are specified in different systems and the implementation of the C language standard library. They are generally described in the header file errno.h. A C language program will use one when it starts. The comprehensive variable errno records the current error code of the program. However, when the program starts, errno is 0, indicating that there is no error. When we use a function in the standard library and an error occurs, it will say The corresponding error code is stored in errno, and the number of an error code is an integer, which is difficult to understand what it means, so each error code has a corresponding error message. The strerror function can return the address of the error message string corresponding to the error.

use:

#include <errno.h>
#include <string.h>
#include <stdio.h>
//我们打印⼀下0~10这些错误码对应的信息
int main()
{
    
    
	int i = 0;
	for (i = 0; i <= 10; i++) {
    
    
		printf("%s\n", strerror(i));
	}
	return 0;
}

operation result:
Insert image description here

The above is what I shared. If there are any mistakes, please leave a message in the comment area.
Finally, thank you everyone for watching!

Guess you like

Origin blog.csdn.net/2302_79539362/article/details/134618691