C language - character functions and string functions_study notes

Regarding the simulation implementation of some string functions, welcome to browse the article C language - simulation implementation of some string functions

1. Character functions

1.1 Character classification function

There are a series of functions in C language that are dedicated to character classification, that is, what type of character a character belongs to. The use of these functions requires a header file <ctype.h>

Introduction to common character classification functions

function Returns true if its parameters meet the following conditions
iscntrl any control character
isspace White space characters: space ' ', form feed '\f, line feed '\n', carriage return '\r', tab '\t' or vertical tab '\v'
even Decimal numbers 0~9
self digit 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 Letters a~z and letters A~Z
the ice hall Letters or numbers, a~ z, A~ Z, 0~9
ispunct Punctuation, any printable graphic character that is not a number or letter
isgraph any graphic character
sprint Any printable character, including graphic characters and whitespace characters

Application examples

The usage of these functions is very similar. We use iscntrl as an example, and the others are very similar:

#include <stdio.h>
#include <ctype.h>
int main ()
{
    
    
  int i=0;
  char str[]="first line \n second line \n";
  while (!iscntrl(str[i]))
  {
    
    
    putchar (str[i]);
    i++;
  }
  return 0;
}
  1. In C language, a "!" symbol represents a logical NOT operation. When it is followed by a Boolean expression, it inverts it. For example, if the result of an expression is true, the "!" operator converts it to false and vice versa.
  2. The iscntrl function returns true on any control character encountered. (\n is a control character)

The meaning of the above code is to traverse the output string array str[] and stop output when encountering a control character. The output
result is:

first line 

1.2 Character conversion function

Function introduction

C language provides 2 character conversion functions:

Function name function effect
tolower Convert lowercase letters in the passed parameters to uppercase letters
toupper Convert uppercase letters in the passed parameters to lowercase letters

If we do not use the library function, we convert lowercase letters to uppercase letters, which is the result of -32 for lowercase letters; converting uppercase letters to lowercase is the result of +32. But with library functions, you can use library functions directly, which is convenient, fast and efficient.

toupper function example

void toUpperCase(char* str) 
{
    
    
    for (int i = 0; str[i] != '\0'; i++) 
    {
    
    
        str[i] = toupper(str[i]);
    }
}

int main() 
{
    
    
    char str[] = "Hello, world!";
    printf("原字符: %s\n", str);
    toUpperCase(str);
    printf("转换后: %s\n", str);
    return 0;
}

The output is as follows:
Insert image description here

2. String functions

When using string functions, be sure to include the <string.h> header file

Regarding the simulation implementation of some string functions, welcome to browse the article C language - simulation implementation of some string functions

2.1 Introduction to commonly used string functions

function function effect
strlen(a) Function used to calculate the length of string a. The return value is a number of size_t type. Header file <string.h>
strcpy(a,b) Used to copy source string b to target string a, including the \0 character. The return value is the address of the first element of string a, header file <string.h>
strcat(a,b) Concatenate the contents of source string b to the end of target string a, and add the terminator \0 to the end of the resulting string. The return value is the address of the first element of string a, header file <string.h>
strcmp(a,b) Compares two strings a and b. If the two strings are exactly the same, the function returns 0; if the string in the first parameter str1 is before the string in the second parameter str2 in lexicographic order, the function returns a Negative integer. If the string in str1 comes lexicographically after the string in str2, the function returns a positive integer.
strncpy(str1,str2,n) Used to copy the first n characters of the source string str2 to the target string str1. The return value is the address of the first element of the string str1. Header file <string.h>
strncat(str1,str2,n) Used to append the first n characters of the source string str2 to the end of the target string str1, and the return value is the address of the first element of the string str1. Header file <string.h>
strncmp(str1,str2,n) The function compares the first n characters of two strings one by one in lexicographic order until a non-matching character is encountered or the end of the string is reached. If the first n characters of the two strings are identical, the function returns 0. If the string in the first parameter str1 precedes the string in the second parameter str2 in lexicographic order by the first n characters, the function returns a negative integer. If the string in str1 precedes the string in str2 lexicographically by the first n characters, the function returns a positive integer. Header file <string.h>
strstr(str1,str2) is to find the first occurrence of str2 string in str1 string. This function returns a pointer to the first occurrence of str2 in str1. If str2 does not appear in str1, the function will return NULL. Header file <string.h>
strtok(str,delim) Used to split a string into a series of substrings. The function will split str according to the characters in delim and return a pointer to the first substring. Each call to the strtok function moves the pointer to the next substring until there are no more substrings. (When splitting a string, the strtok function ignores leading and trailing spaces in the string. If the delimiter string is NULL, spaces are used as the delimiter by default.) Header file <string.h>

2.2 Application examples

①strlen

The function prototype is as follows:

#include <string.h>

size_t strlen(const char *str);
  1. This function accepts a pointer to a string as argument and returns the length of the string, excluding the null character ('\0') at the end of the string.

  2. The strlen function uses a pointer to iterate through each character in the string until a null character is encountered. It counts the number of characters traversed and returns the result.

Here is an example using the strlen function:

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

int main() {
    
    
    char str[] = "Hello, world!";
    printf("Length of string: %zu\n", strlen(str));
    return 0;
}

In this example, the strlen function calculates the length of the string str and prints the result using the printf function. Note that we use the %zu format specifier to output the return value of the strlen function because its return type is size_t.

The output is:

Insert image description here

② strcpy

The function prototype is as follows:

#include <string.h>

char *strcpy(char *dest, const char *src);
  1. dest is a pointer to the destination string, and src is a pointer to the source string.

  2. The strcpy function copies the source string into the destination string, including the terminator \0. It returns a pointer to the target string.

Here is an example using the strcpy function:

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

int main() {
    
    
    char src[30] = "Hello, world!";
    char dest[30];

    strcpy(dest, src);
    printf("Source string: %s\n", src);
    printf("Destination string: %s\n", dest);

    return 0;
}

In this example, the strcpy function copies the string in src to dest, and then outputs the two strings through the printf function.

The output is as follows:
Insert image description here

③ cracked

The function prototype is as follows:

#include <string.h>

char *strcat(char *dest, const char *src);
  1. Among them, dest is the pointer of the target string, and src is the pointer of the source string to be connected.

  2. The strcat function appends the source string to the end of the destination string and adds a terminator \0 to the end of the result string. It returns a pointer to the target string.

Here is an example using the strcat function:

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

int main() {
    
    
    char dest[30] = "Hello, ";
    char src[30] = "world!";

    strcat(dest, src);
    printf("Result string: %s\n", dest);

    return 0;
}

In this example, the strcat function appends the string in src to the end of dest, and then outputs the resulting string through the printf function.

The output is as follows:
Insert image description here

④ strcmp

The function prototype is as follows:

#include <string.h>

int strcmp(const char *str1, const char *str2);
  1. Among them, str1 and str2 are pointers to the two strings to be compared.

  2. The strcmp function compares two strings lexicographically and returns their difference. If the two strings are exactly the same, return 0; if the first string is smaller than the second string, return a negative number; if the first string is larger than the second string, return a positive number .

Here is an example using the strcmp function:

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

int main() {
    
    
    char str1[] = "Hello";
    char str2[] = "hello";
    int result = strcmp(str1, str2);

    if (result == 0) {
    
    
        printf("Strings are equal.\n");
    } else if (result < 0) {
    
    
        printf("String 1 is less than string 2.\n");
    } else {
    
    
        printf("String 1 is greater than string 2.\n");
    }

    return 0;
}

In this example, the strcmp function compares two strings, str1 and str2, and outputs a corresponding message based on the comparison result.

The output is:

Insert image description here

⑤ strncpy

Prototype of strncpy function:

char *strncpy(char *dest, const char *src, size_t n);

Here is an example using the strncpy function:

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

int main() {
    
    
    char dest[10] = "Hello";
    const char src[] = " World";
    strncpy(dest, src, 5);
    printf("%s\n", dest);  // 输出:Hello W
    return 0;
}

In this example, we have a target string "Hello" and a source string "World". We use the strncpy function to copy the first 5 characters of the source string to the target string, and the result is "Hello W". Note that because the destination array only has 10 spaces, we only copy the first 5 characters, not the entire source string. At the same time, because we have not reserved space for the target array to add null characters, the final output does not automatically add null characters.

⑥ strncat

The prototype definition of this function:

char *strncat(char *dest, const char *src, size_t n);

Here is an example using the strncat function:

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

int main() {
    
    
    char dest[10] = "Hello";
    const char src[] = " World";
    strncat(dest, src, 4);
    printf("%s\n", dest);  // 输出:Hello World
    return 0;
}

In this example, we have a target string "Hello" and a source string "World". We use the strncat function to append the first 4 characters of the source string to the end of the target string, and the result is "Hello World".

⑦ strncmp

Prototype definition of strncmp function:

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

Here is an example using the strncmp function:

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

int main() {
    
    
    const char str1[] = "Hello";
    const char str2[] = "Hell";
    int result = strncmp(str1, str2, 4);
    if (result < 0) {
    
    
        printf("%s is less than %s\n", str1, str2);
    } else if (result > 0) {
    
    
        printf("%s is greater than %s\n", str1, str2);
    } else {
    
    
        printf("%s is equal to %s\n", str1, str2);
    }
    return 0;
}

The output is:

Insert image description here

⑧ strstr

The prototype of strstr function is:

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

Here is an example using the strstr function:

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

int main() {
    
    
    const char *haystack = "Hello, world!";
    const char *needle = "world";
    const char *result = strstr(haystack, needle);

    if (result) {
    
    
        printf("'%s' found in '%s' at position: %ld\n", needle, haystack, result - haystack);
    } else {
    
    
        printf("'%s' not found in '%s'\n", needle, haystack);
    }

    return 0;
}

This code will output: "'world' found in 'Hello, world!' at position: 7", because the first occurrence of "world" in "Hello, world!" is the seventh position from the string character begins.

⑨ strtok

The prototype of strtok function is:

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

The following is an example using the strtok function:

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

int main() {
    
    
    char str[] = "Hello, World! How are you?";
    const char delim[] = " ,!";
    char *token;

    token = strtok(str, delim);
    while (token != NULL) {
    
    
        printf("%s\n", token);
        token = strtok(NULL, delim);
    }

    return 0;
}

This code will split the string "Hello, World! How are you?" into multiple substrings and output each substring. The output will be:

Hello
World
How
are
you?

Regarding the simulation implementation of some string functions, welcome to browse the article C language - simulation implementation of some string functions

Guess you like

Origin blog.csdn.net/yjagks/article/details/132731162
Recommended