C语言截取字符串

1.从左边截取指定长度的字符串

代码功能:从字符串开头,截取指定长度的字符。

#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;
}

运行结果:

input a data
hurytdxcgf
hur

2.从右边截取指定长度的字符串

代码功能:从字符串末尾,截取指定长度的字符。

#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;
}

运行结果:

input a data
asfafg
len=6
gf

3.利用strstr查找字符串

代码功能:查找字符串中是否包含字符"s"

#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;
}

输出结果 :

input a data
dsfgfda
middle positiom

4.使用strtok函数,从指定字符后截取数据。

代码功能:截取字符"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;
}

运行结果: 

input a data
abcd123
middle positiom
distance=123
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LJX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值