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

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

#include #include 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 datahurytdxcgfhur

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

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

#include #include 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 dataasfafglen=6gf

3.利用strstr查找字符串

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

#include #include #include #include #include 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 datadsfgfdamiddle positiom

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

代码功能:截取字符”d”后的所有数据

#include #include #include #include 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 dataabcd123middle positiomdistance=123