03-C language advanced-character function and string function


The processing of characters and strings in C language is very frequent, but the C language itself does not have a string type. Strings are usually placed in constant strings or character arrays. String constants are suitable for those string functions that do not modify it.

One, string manipulation function

1. Find the length of the string

1.1 strlen

size_t strlen(const char *str);
  • The string ends with '\0' , and the strlen function returns the number of characters that appear before'\0' in the string .
    Note : "\0" is not included here, such as "abc", the value returned by strlen is 3.
  • The string pointed to by the parameter must end with'\0'.
    Note : The return value of the function is size_t, which is an unsigned integer (error-prone), for example:
int main()
{
    
    
    const char*str1 = "abcdef";
    const char*str2 = "bbb";
    if(strlen(str2)-strlen(str1)>0)
    {
    
    
        printf("str2>str1\n");
    } 
    else
    {
    
    
        printf("srt1>str2\n");
    }
    return 0;
}

Result Insert picture description here
Reason: The return value of strlen is unsigned integer, so there will be no negative number, and no less than 0.

2. String with unlimited length

2.1 strcpy

char * strcpy(char * destination, const char * source);
  • Copy the C string pointed to by source to the array pointed to by destination, including'\0' .
    note:
  • The source string must end with'\0'.
  • The'\0' in the string will be copied to the target space.
  • The target space must be large enough to ensure that the source string can be stored.
  • The target space must be variable.
  • The source will not be modified and can only be read, so use const.

2.2 strcat

char * strcat(char * destination, const char * source);
  • Append the first numeric character of the source to the target, plus a terminating null character
  • If the length of the C string in the source is less than num, only the content up to the terminating null character is copied.
  • The source string must end with'\0'.
  • The target space must be large enough to hold the content of the source string.
  • The target space must be modifiable.

2.3 strcmp

int strcmp(const char * str1, const char * str2 );

How to compare the size of two strings?
This function compares the first character of each string. If they are equal, continue to compare the second character until the characters are different or the'\0' character. The size of the string has nothing to do with the length.
The principle of character comparison is the code value of the ascll table , as shown in the figure below. For example: "abc", "abd", the first two characters a, b have the same ascll code value, compare c and d, you can get c=99<d=100, so "abd">"abc".
[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-2bKa0lBl-1606184717461)(https://baike.baidu.com/pic/ASCII/309296/1/e850352ac65c103880a07b53bc119313b17e8941 ?fr=lemma#aid=1&pic=e850352ac65c103880a07b53bc119313b17e8941#pic_center)]
What needs to be noted here is the return value of strcmp:

  • standard regulation:
    • If the first string is greater than the second string, a number greater than 0 is returned
    • If the first string is equal to the second string, 0 is returned
    • If the first string is less than the second string, a number less than 0 will be returned.
      Example:
const char * str1 = "abc";
const char * str2 = "abc";

if (strcmp(str1, str2))
{
    
    
	printf("相等\n");
}
else
{
    
    
	printf("不相等\n");
}

Result: Insert picture description here
Reason: If the two strings are equal, the return value of strcmp is 0. The correct wording is as follows :

const char * str1 = "abc";
const char * str2 = "abc";

if (strcmp(str1, str2)==0)
{
    
    
	printf("相等\n");
}
else
{
    
    
	printf("不相等\n");
}

result:Insert picture description here

3. Introduction to string functions with restricted length

3.1 strncpy

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

Copy the first few characters of the source to the target. If the end of the source C string (represented by a null character) is found before the numeric characters are copied, the target will be filled with zeros until a total of numeric characters are written into it.
Copy num characters from the source string to the target space.
If the length of the source string is less than num, after copying the source string, 0 is appended to the end of the target until num.

3.2 strncat

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

Append the first few characters of the source to the target, plus a terminating null character. If the length of the C string in the source is less than num, only the content up to the terminating null character is copied.

Note: strncpy will not automatically add'\0', but strncat will automatically add'\0' .
example:

char str1[20];
char str2[20];
strcpy(str1, "To be ");
strcpy(str2, "or not to be");
strncat(str1, str2, 6);
puts(str1);

Result: Insert picture description here
Here you need to understand the puts function

int puts ( const char * str );

C language has three input and output functions by default

  • stdin: standard input -> keyboard
  • stdout: standard output -> display
  • stderror: standard error -> display

The difference between puts and printf:

	puts("hello world %d\n");
	printf("hello world %d\n", 10);

Insert picture description here
Puts carries a "\n" by default.

3.3 strncmp

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

The comparison shows that another character is different or the end of a string or num characters are all compared.
example:

char str[][5] = {
    
     "R2D2","B7UD","R2O9" };
int n;
puts("Looking for R2 astromech droids...");
for (n = 0; n < 3; n++)
{
    
    
	if (strncmp(str[n], "R2xx", 2) == 0)
	{
    
    
		printf("founds %s\n",str[n]);
	}
}

result:Insert picture description here

4. String search

4.1 strstr

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

Return a pointer to the first occurrence of str2 in str1. If str2 is not part of str1, return a null pointer.
Example:

char str[] = "This is a simple string.";
char *pch;
pch = strstr(str, "simple");
strncpy(pch, "sample", 6);
puts(str);

result:Insert picture description here

4.2 strtok

char * strtok( char * str, const char * sep)
  • The sep parameter is a string that defines the set of characters used as a separator.
  • The first parameter specifies a string, which contains 0 or more tokens separated by one or more separators in the sep string.
  • The strtok function finds the next token in str, ends it with \0, and returns a pointer to this token. (Note: The strtok function will change the string being manipulated, so the string split using the strtok function is generally a temporary copy of the content and can be modified.)
  • 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.
  • The first parameter of the strtok function is NULL, and the function will start at the saved position in the same string and look for the next token.
  • If there are no more tokens in the string, a NULL pointer is returned.
    Note: strtok is used for string segmentation. The first call needs to pass in the starting address of the string, and the subsequent calls can be set to NULL, and one string at a time.
    Example: Separate strings with @ and.
	char *p = "[email protected]";
	const char* sep = ".@";
	char arr[30];
	char *str = NULL;
	strcpy(arr, p);//将数据拷贝一份,处理arr数组的内容
	for (str = strtok(arr, sep); str != NULL; str = strtok(NULL, sep))
	{
    
    
		printf("%s\n", str);
	}

result:Insert picture description here

5. Error information report

5.1 strerror

char * strerror(int errnum);

The call to the function must include the header file

#include<errno.h>

Return the error code and the corresponding error message.
Example: View the information corresponding to the error code under windows

for (int i = 1; i < 50; i++)
{
    
    
	printf("%d->%s\n", i, strerror(i));
}

result:Insert picture description here

Two, character operation

1. Character classification function

The character operation judged is the result of a single character, which needs to be distinguished from the character string and should not be confused.

function If his parameter meets the following conditions, it returns true
iscntrl Any control character
isspace Blank characters: space '', page feed'\f', line feed'\n', carriage return'\r', tab character'\t' or vertical tab character'\v'
isdigit Decimal digits 0~9
isxdigit Hexadecimal numbers, including all decimal numbers, lowercase letters a f, uppercase letters A F
islower Lowercase letters a~z
isupper Capital letters A~Z
isalpha A letter Z or A the Z
isalnum Letters or numbers, a z,A Z,0~9
ispunct Punctuation marks, any graphic characters that are not numbers or letters (printable)
isgraph Any graphic character
print Any printable characters, including graphic characters and blank characters

Example: Determine whether the character c is a space

char c = ' ';
if (isspace(c))
{
    
    
	printf("c为空格\n");
}

Insert picture description here

2. Character conversion

int tolower ( int c );
int toupper ( int c );

Example: Convert uppercase letters in a string to lowercase letters

int i = 0;
char str[] = "Test String.\n";
char c;
while (str[i])
{
    
    
	c = str[i];
	if (isupper(c))
		c = tolower(c);
	putchar(c);
	i++;
}

Insert picture description here

Three, memory operation function

Note: The basic unit of memory copy operation is byte, which has nothing to do with type. For examples, see the memset operation function example

1.memcpy

void * memcpy (void * destination, const void * source, size_t num)
  • The function memcpy copies num bytes of data from the location of the source to the memory location of the destination.
  • Unlike the string copy function strcpy, this function does not stop when it encounters'\0', but copies num bytes accurately.
  • If there is any overlap between source and destination, the result of copying is undefined
    memcpy can copy the structure, for example:
struct {
    
    
		char name[16];
		int age;
	}person,person_copy;

	char myname[] = "kyrie";
	memcpy(person.name, myname, strlen(myname) + 1);
	person.age = 46;

	/* using memcpy to copy structure: */
	memcpy(&person_copy, &person, sizeof(person));

	printf("person_copy: %s, %d \n", person_copy.name, person_copy.age);

Insert picture description here

It should be noted here that memcpy passes in the address

2.memmove

void * memmove ( void * destination, const void * source, size_t num ); 

3.memset

void * memset ( void * ptr, int value, size_t num );

ptr: is a pointer or an array,
value: is the value assigned to ptr,
num: is the length of ptr.
Here you need to remember: the basic unit of mem operation is byte, which has nothing to do with type.
Example:

int a[5] = {
    
     0 };
memset(a, 1, sizeof(a));
for (int i = 0; i < 5; i++)
	printf("a[%d]=%d\n", i, a[i]);

Misunderstanding : Assign 1 to each value of the integer array a , this kind of understanding is wrong.
Correct understanding: Assign 1 to each byte of the integer array a
Insert picture description here
Insert picture description here

4.memcmp

int memcmp ( const void * ptr1,  
    const void * ptr2,  
    size_t num ); 

Compare num bytes starting from the pointers of ptr1 and ptr2
Example: Compare the size of two strings

char buffer1[] = "DWgaOtP12df0";
char buffer2[] = "DWGAOTP12DF0";

int n;

n = memcmp(buffer1, buffer2, sizeof(buffer1));

if (n>0) printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
else if (n<0) printf("'%s' is less than '%s'.\n", buffer1, buffer2);
else printf("'%s' is the same as '%s'.\n", buffer1, buffer2);

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40076022/article/details/109893212