将字符串解析为多个变量 [英] Parse string to multiple vars
问题描述
嘿,我在尝试解析字符串时遇到问题. 我的程序可以接收4种类型的输入:
Hey Im having a problem trying to parse strings. My program can receive 4 types of input:
s = "x=10+2;"
s = "x=10+y;"
s = "x=y+10;"
s = "x=y+z;"
我的意思是格式如下:s = "(string)=(string)||(int)+(string)||(int);"
I mean the format is something like: s = "(string)=(string)||(int)+(string)||(int);"
我尝试使用sscanf( s, "%c=%d+%d", &c, &v1, &v2 )
但是我首先需要验证输入是哪种类型.
I have tried to use sscanf( s, "%c=%d+%d", &c, &v1, &v2 )
but I need to first verify which type of input is it.
char* s = "x=2+22;";
int v1, v2;
char* c;
sscanf( s, "%c=%d+%d", &c, &v1, &v2 );
printf("%s %d %d\n", c, v1, v2);
我想将字符串解析为三个变量.
I want to parse the string to three vars.
推荐答案
让我为您提出另一种方法,使用strsep
和某些if
条件来检测字符是整数还是字符串,以下代码适用于所有您的案件
Let me propose you another way, using strsep
and some if
conditionals to detect if the characters are integer or string, the following code works for all your cases
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *token, *string, *var;
char *str = "x=x+10;";
int tmp1,tmp2;
tofree = string = strdup(str);
if (string == NULL)
return -1;
token = strsep(&string, "=");
printf("%s\n", token);
token = strsep(&string, "=");
printf("%s\n", token);
var = strsep(&token, "+");
if( var[0] >= 0x60 && var[0] <= 0x7B ) // detect string
{
printf("str1 = [ %s ] \n", var);
} else { // else case will be an integer
tmp1 = atoi(var);
printf("int1 = [ %d ] \n ",tmp1);
}
var = strsep(&token, "+");
var[strlen(var)-1]='\0'; // remove ";"
if( var[0] >= 0x61 && var[0] <= 0x7A )
{
printf("str2 = [ %s ] \n", var);
}else{
tmp2 = atoi(var);
printf("int2 = [ %d ] \n ",tmp2);
}
return 0;
}
这篇关于将字符串解析为多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!