Parse string to multiple vars

2019-08-27 20:44发布

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;"

I mean the format is something like: s = "(string)=(string)||(int)+(string)||(int);"

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.

标签: c regex parsing
1条回答
【Aperson】
2楼-- · 2019-08-27 20:57

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;
}
查看更多
登录 后发表回答