C language intercept string

1. Intercept a string of specified length from the left

Code function: From the beginning of the string, intercept characters of the specified length.

#include <stdio.h>
#include <wiringPi.h>

int main()
{
        char arr[128] = {'\0'};
        int i = 0;

        printf("input a data\n");
        scanf("%s",arr);

        for(i=0;i<3;i++){   //截取前三个字符
                printf("%c",arr[i]);
        }
        return 0;
}

operation result:

input a data
hurytdxcgf
hur

2. Intercept a string of specified length from the right

Code function: From the end of the string, intercept characters of the specified length.

#include <wiringPi.h>
#include <string.h>

int main()
{
        char arr[128] = {'\0'};
        int i = 0;

        printf("input a data\n");
        scanf("%s",arr);

        int len = strlen(arr);
        printf("len=%d\n",len);

        for(i=len;i>(len-3);i--){
                printf("%c",arr[i]);
        }
        return 0;
}

operation result:

input a data
asfafg
len=6
gf

3. Use strstr to find a string

Code function: Find whether the character "s" is contained in the string

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

int main()
{
        char arr[128] = {'\0'};
        char *p = "s";

        printf("input a data\n");
        scanf("%s",arr);

        if(strstr(arr,p) == NULL){
                printf("not find position\n");
        }else{
                printf("middle positiom\n");
        }
        return 0;
}

Output result:

input a data
dsfgfda
middle positiom

4. Use the strtok function to intercept data after the specified character.

Code function: intercept all data after the character "d"

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

int main()
{
        char arr[128] = {'\0'};
        char *pos_state = "d";
        char *token;

        printf("input a data\n");
        scanf("%s",arr);

        if(strstr(arr,pos_state) == NULL){
                printf("not find position\n");
        }else{
                printf("middle positiom\n");
        }
        char *buf = strstr(arr,pos_state);
        token = strtok(buf, "d");
        printf("distance=%s\n",token);
        token = strtok(NULL, "d");
        return 0;
}

operation result: 

input a data
abcd123
middle positiom
distance=123

Guess you like

Origin blog.csdn.net/aaaaaaaa123345/article/details/129739120