C ++ notes (4) - string.h related to some small knowledge

strlen()

The first array of characters for obtaining a \0number of characters before the following format:

strlen(数组);

example:

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

int main(){
    char str[10];
    gets(str);
    int len = strlen(str);
    printf("%d\n", len);
    return 0;
} 

Input:

ababab

Output:

6

strcmp()

For comparing the size of the string, the principle of the comparison is in lexicographic order:

strcmp(字符数组1, 字符数组2)

If the length of the array 1 returns a positive number, it returns an array of length 2 negative, return is equal to 0.

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

int main(){
    char str1[50], str2[50];
    gets(str1);
    gets(str2);
    int cmp = strcmp(str1, str2);
    if(cmp < 0) printf("str1 < str2\n");
    else if (cmp > 0) printf("str1 > str2\n");
    else printf("str1 == str2\n");
    return 0;
}

Figure above the first two lines are input, the last line is output.

strcpy()

Copy string to another string, use: strcpy(str1, str2). This will str2copy the contents str1.

Example:

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

int main(){
    char str1[50], str2[50];
    gets(str1);
    gets(str2);
    strcpy(str1, str2);
    puts(str1);
    return 0;
}

strcat()

Splicing two strcat(str1, str2)strings ,

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

int main(){
    char str1[50], str2[50];
    gets(str1);
    gets(str2);
    strcat(str1, str2);
    puts(str1);
    return 0;
}

sscanf与sprintf

sscanfAnd sprintfit is designed for use with strings, can be understood as "string + scanf" and "string + printf".

It is similar to the usage in memory scanfand printfthe way data transfer. For example, sscanf(str, "%d", &n);this is in str content %dwritten in a format to n (this can be appreciated, scanf(screen, "%d", &n);corresponding to the input from the screen is a screen capture and input to the n, from left to right, and sscanfthe role of this almost , according to the str "%d"input format to n. sprintfis, in turn, from right to left).

Relatively simple, direct on the sample:

#include <stdio.h>

int main() {
    int n;
    char str[100] = "123";
    sscanf(str, "%d", &n);
    printf("%d\n", n);
    return 0;
} 

#include <stdio.h>

int main(){
    int n = 233;
    char str[100];
    sprintf(str, "%d", n);
    printf("%s\n", str);
    return 0;
}

Examples of complex points:

#include <stdio.h>

int main(){
    int n;
    double db;
    char str[100] = "2048:3.14, hello", str2[100];
    sscanf(str, "%d:%lf, %s", &n, &db, str2);
    printf("n = %d, db = %.2f, str2 = %s\n", n, db, str2);
    return 0;
}

Quite useful when string handling.

Guess you like

Origin www.cnblogs.com/yejianying/p/cpp_notes_4.html