如何将运行时变量替换为c中的字符串?

时间:2015-01-23 05:52:11

标签: c string

我正在尝试编写一个c程序,它接受一个公式并用用户提供的值代替字母变量。

Eg:
char formula[50]= "x+y+x"  //this is a string. Can also be given at runtime
char sub[50];//This is where my substitutions should go
printf("enter substitutes");
fgets(sub, sizeof(sub), stdin);
//user inputs x=1,y=2

现在,我如何将sub中提供的值替换为公式字符串?

1 个答案:

答案 0 :(得分:1)

  1. 使用fgets()将表达式读取到char数组公式,因为您说它可以在运行时给出。
  2. 现在使用sub
  3. 获取另一个char数组fgets()
  4. 假设数组formula中需要替换的字符数匹配正确匹配sub传递的值
  5. 现在解析您的数组formula使用isalpha(),如果是,则将您的字符替换为sub中存储的值。
  6. 现在你有。
  7. Formula = "x+y+z";
    Sub = "123";
    
    Formula = "1+2+3";
    

    检查以下代码:

    #include <stdio.h>
    #include<ctype.h>
    #include<string.h>
    
    int main(void) {
        int n,i=0,j=0;
        char a[20];
        char sub[20];
    
        fgets(a,sizeof(a),stdin);/* Get input from the user for formula*/
        n = strlen(a);
        if(n > 0 && a[n - 1] == '\n')
        a[n- 1] = '\0';
        fgets(sub,sizeof(sub),stdin);/* Get input from the user for sub*/
        n = strlen(sub);
        if(n>0 && sub[n-1] == '\n')
        sub[n-1] = '\0';
        printf("%s\n",a); /* Formula before substituting */
        while(a[i] != '\0')
        {
            if(isalpha(a[i]))/* If alpahbet replace with sub */
            {
                a[i] = sub[j];
                j++;
            }
            i++;
        }
    
        printf("%s\n",a);
        return 0;
    }
    

    输出:

    x+y+z
    1+2+3
    
相关问题