Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute runtime variables into strings in c?

Tags:

c

string

I am trying to write a c program that takes in a formula and substitutes user supplied values in place of the alphabetic variables.

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

Now, How do I substitute the values supplied in sub to the formula string?

like image 294
Tania Avatar asked Mar 14 '26 00:03

Tania


1 Answers

  1. Read the expression to your char array formula using fgets() since you say it can be given during run-time.
  2. Now get the other char array sub using fgets()
  3. Assuming there is right match of number of characters needs to be replaced in the array formula matches the values passed by sub
  4. Now parse your array formula use isalpha() and if it is then replace your character with value stored in sub.
  5. Now you have.
Formula = "x+y+z";
Sub = "123";

Formula = "1+2+3";

Check the below code:

#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;
}

Output:

x+y+z
1+2+3
like image 71
Gopi Avatar answered Mar 16 '26 15:03

Gopi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!