C language string related functions use example strtok_r strstr strtok atoi

Through a practical small application, record 4 functions related to string manipulation in C language and their usage:

  • strtok_r

  • sstrstr

  • sstrtok

  • satoi

The question leads
to the first post a variable definition:


char str[] = "led,100,0,80,15";//一个字符串,第一个逗号前的字符串设定为某个命令,后面的是参数

Suppose a certain application scenario receives a string of strings, such as str[] = "led,100,0,80,15" above, separated by commas, assuming that the first string led of the string represents a A kind of instruction, such as turning on the led, the number behind indicates the parameter, such as the brightness value of different leds.

C language string related functions use example strtok_r strstr strtok atoi

So, how should the computer distinguish each character string and obtain the corresponding numeric parameter?

The following introduces several functions in the C language to solve this problem.

Function introduction and example
strtok_r
first needs to divide the string into instruction and parameter forms, and the strtok_r function is needed.

Function definition:


char *strtok_r(char * __restrict__ _Str, const char * __restrict__ _Delim, char ** __restrict__ __last);
  • Parameters: original string, separator, remaining string after splitting

  • Return value: the segmented string, if there is no matching string, a null pointer is returned

Note: This function is a destructive operation, the original string str will be changed after the split processing, and become a split string! ! !

We pass in the str in the above question as the original string, the separator is a comma, and the split is stored in the paras variable defined above, and the return value is stored in the cmd variable defined above:


char *cmd;//表示命令
char *paras;//表示命令后的参数

cmd = strtok_r(str, ",", &paras);
printf("cmd:%s\r\n", cmd);//获得字符串的第一串字符
printf("paras:%s\r\n", paras);//获取后续字符串

View test results:


cmd:led
paras:100,0,80,15

You can see that the two strings of commands and parameters we need are successfully split.


For strstr to obtain the parameter command string, we may also need to determine whether the command is valid, that is, whether the computer has stored the string before, and this test can be simulated by matching the string to the corresponding string in the array. Need to use strstr function, its function is defined as:


char *strstr(const char *_Str,const char *_SubStr);
  • Parameters: the original string, the substring to be searched

  • Return value: the address of the first occurrence of the substring in the source string, otherwise NULL is returned

We can first customize a string array funname[5] for query, and then perform matching and comparison in turn.


char *funname[5] = {"music", "play", "A_led1", "led2", "led"};//自定义的函数名称列表
char *ret;
int i;
for (i = 0; i < 5;i++)
{
    ret = strstr(funname[i], cmd);
    if(ret!=NULL)
    {
        printf("find cmd in funname[%d]\r\n", i);
        printf("ret:%s\r\n", ret);
        break;
    }
}
if(i==5)
{
    printf("can't find cmd in funname[]");
}

Test Results:


find cmd in funname[2]
ret:led1

The cmd string here is the led segmented above. This time it matches the led character contained in A_led1. Because the test code is set to break out of the for loop as long as it finds a match, there is no match to the last exactly the same string. , So pay attention to the actual programming.

In actual use, if you use strstr to match strings, you can define the difference between different strings to ensure correct distinction. The funname defined in the test is just to demonstrate the use of strstr.

strtok has
determined the validity of the command string. Next, we need to split the following parameters. In fact, we can continue to use the strtok_r method. However, we can use another similar function strtok, one of which is used to save cuts. For the parameters of the divided string, the function is defined as follows:


char *strtok(char * __restrict__ _Str,const char * __restrict__ _Delim);
  • Parameters: original string, separator

  • Return value: the segmented string, if there is no matching string, a null pointer is returned

Note: When using this function for the first time, you need to pass in the original string, and for subsequent continuous use, you need to pass in NULL. In fact, after the first operation, the original string passed in has been changed to the first split String.


char* para[4];
para[0] = strtok(paras, ",");
int j= 1;
while(paras != NULL)
{
    para[j++] = strtok(NULL, ",");
    if(j==4)
        break;
}
printf("para[0]:%s\r\n", para[0]);
printf("para[1]:%s\r\n", para[1]);
printf("para[2]:%s\r\n", para[2]);
printf("para[3]:%s\r\n", para[3]);

operation result:


para[0]:100
para[1]:0
para[2]:80
para[3]:15

It can be seen that the following parameters have also been successfully separated.


The parameter number separated above atoi is a string type, and its corresponding integer form may be needed in actual use. We can use the atoi function to convert:


int atoi(const char *_Str);
  • Parameters: a string of numbers

  • Return value: the corresponding integer value, if it cannot be converted, return 0

int p1,p2,p3,p4;
p1= atoi(para[0]);
p2= atoi(para[1]);
p3= atoi(para[2]);
p4= atoi(para[3]);
printf("%d,%d,%d,%d\r\n",p1,p2,p3,p4);


测试结果:

100,0,80,15


%d形式的打印也正确,说明转换成功。

另外,可以测试一下atoi的其它使用情况:

//Test the string that cannot be converted to a number
printf("atoi(hello): %d\r\n", atoi("hello"));
//Test the floating-point string
printf("atoi(3.14): %d\r\n", atoi("3.14"));


输出:

atoi(hello): 0
atoi(3.14): 3


可以看出,不能转换的会返回0,浮点型字符串只返回整数部分。

至此,文章开头提出的问题已经解决,下面贴出完整测试代码。

**完整测试程序**

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

int main()
{
char funname[5] = {"music", "play", "A_led1", "led2", "led"};//list of custom function names
char str[] = "led,100 ,0,80,15";//A character string, the character string before the first comma is set to a certain command, and the following is the parameter
char
cmd; // indicates the command
char *paras;// indicates the command after the command Parameter
printf("str=%s\r\n", str);

//strtok_r==================================
/*
char *strtok_r(char * __restrict__ _Str, const char * __restrict__ _Delim, char ** __restrict__ __last);
参数:原始字符串,分隔符,切分后剩余的字符串
返回值:切分掉的字符串
*/
printf("\r\ntest [strtok_r] --------------------->\r\n");
cmd = strtok_r(str, ",", &paras);
printf("cmd:%s\r\n", cmd);//获得字符串的第一串字符
printf("paras:%s\r\n", paras);//获取后续字符串
printf("str:%s\r\n",str);//------原str已经被破坏了!!!

//strstr=====================================
/*
char *strstr(const char *_Str,const char *_SubStr);
参数:原始字符串,要查找的子字符串
返回值:子字符串在源字符串中首次出现的地址,无则返回NULL
*/
printf("\r\ntest [strstr] --------------------->\r\n");
char *ret;
int i;
for (i = 0; i < 5;i++)

{
ret = strstr(funname[i], cmd);
if(ret!=NULL)
{
printf("find cmd in funname[%d]\r\n", i);
printf("ret:%s\r\n", ret);
break;
}
}
if(i==5)
{
printf("can't find cmd in funname[]");
}

//strtok====================================
/*
char *strtok(char * __restrict__ _Str,const char * __restrict__ _Delim)
参数:原始字符串,分隔符
返回值:切分掉的字符串
*/
printf("\r\ntest [strtok] --------------------->\r\n");
char* para[4];
para[0] = strtok(paras, ",");
int j= 1;
while(paras != NULL)

{
para[j++] = strtok(NULL, ",");
if(j==4)
break;
}
printf("para[0]:%s\r\n", para[0]);
printf("para[1]:%s\r\n", para[1]);
printf("para[2]:%s\r\n", para[2]);
printf("para[3]:%s\r\n", para[3]);

//字符串转数字================================
/*
int atoi(const char *_Str);
参数:字符串
返回值:字符串对应的数字值
*/
printf("\r\ntest [atoi] --------------------->\r\n");
int p1,p2,p3,p4;
p1= atoi(para[0]);
p2= atoi(para[1]);
p3= atoi(para[2]);
p4= atoi(para[3]);
printf("%d,%d,%d,%d\r\n",p1,p2,p3,p4);

//测试不能转化为数字的字符串
printf("atoi(hello): %d\r\n", atoi("hello"));

//测试浮点型字符串
printf("atoi(3.14): %d\r\n", atoi("3.14"));

return 0;

}


运行结果:

str=led,100,0,80,15

test [strtok_r] --------------------->
cmd:led
paras:100,0,80,15
str:led

test [strstr] --------------------->
find cmd in funname[2]
ret:led1

test [strtok] --------------------->
para[0]:100
para[1]:0
para[2]:80
para[3]:15

test [atoi] --------------------->
100,0,80,15
atoi(hello): 0
atoi(3.14): 3

Guess you like

Origin blog.51cto.com/15060517/2641132