【STM32】利⽤C语⾔strchar()函数查字符串中指定字符的位置⽂章⽬录
字符串中查字符 strchr()
描述
C 库函数 char *strchr(const char *str, int c) 在参数 str 所指向的字符串中搜索第⼀次出现字符 c(⼀个⽆符号字符)的位置。声明
下⾯是 strchr() 函数的声明。
char*strchr(const char*str,int c)
参数
str – 要被检索的 C 字符串。
c – 在 str 中要搜索的字符。
返回值
该函数返回在字符串 str 中第⼀次出现字符 c 的位置,如果未到该字符则返回 NULL。
#include<stdio.h>
#include<string.h>
int main()
{
const char str[]="www.runoob";
const char ch ='.';
char*ret;
ret =strchr(str, ch);
printf("|%c| 之后的字符串是 - |%s|\n", ch, ret);
return(0);
}
结果为:
|.|之后的字符串是-|.runoob|
字符串分割 strtok()
描述
C 库函数 char *strtok(char *str, const char *delim) 分解字符串 str 为⼀组字符串,delim 为分隔符。
声明
下⾯是 strtok() 函数的声明。
char*strtok(char*str,const char*delim)
参数
str – 要被分解成⼀组⼩字符串的字符串。
delim – 包含分隔符的 C 字符串。
返回值
该函数返回被分解的第⼀个⼦字符串,如果没有可检索的字符串,则返回⼀个空指针。
#include<string.h>
#include<stdio.h>
int main(){
char str[80]="This is - www.runoob - website";
const char s[2]="-";
char*token;
/* 获取第⼀个⼦字符串 */
token =strtok(str, s);
/* 继续获取其他的⼦字符串 */
while( token !=NULL){
printf("%s\n", token );
token =strtok(NULL, s);
}
return(0);
}
结果为:
This is
www.runoob
website
⾃⼰的函数
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str[]="标签坐标: X = 28889 cm , Y = 36 cm, Z = 8 cm"; char*token;
int XPos=0, YPos=0, ZPos=0;
/* 获取第⼀个⼦字符串 */
token =strtok(str," ");
//printf("%s\n", token);
/* 继续获取其他的⼦字符串 */
while(token !=NULL)
{
if(*token =='X')
{
token =strtok(NULL," ");//printf("%s\n", token);
token =strtok(NULL," ");//printf("XPos=%s\n", token);            XPos =atoi(token);
}
c语言char的用法if(*token =='Y')
{
token =strtok(NULL," ");//printf("%s\n", token);
token =strtok(NULL," ");//printf("YPos=%s\n", token);            YPos =atoi(token);
}
if(*token =='Z')
{
token =strtok(NULL," ");//printf("%s\n", token);
token =strtok(NULL," ");//printf("ZPos=%s\n", token);            ZPos =atoi(token);
}
token =strtok(NULL," ");//printf("%s\n", token);
}
printf("%d\n", XPos);
printf("%d\n", YPos);
printf("%d\n", ZPos);
return(0);
}
结果为:
28889
36
8
Ref:
1.
2.
3.

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。