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

标签 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. 使用 fgets() 将表达式读入您的 char 数组公式,因为您说它可以在运行时给出。
  2. 现在使用 fgets()
  3. 获取另一个字符数组 sub
  4. 假设数组中需要替换的字符数正确匹配 formulasub 传递的值匹配
  5. 现在使用 isalpha() 解析您的数组 formula,如果是,则将您的字符替换为存储在 sub 中的值。
  6. 现在你有。
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

关于c - 如何将运行时变量替换为 c 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28103840/

相关文章:

c - 使用 sprintf 制作格式字符串

c - long long 和 long 在 64 位机器的 C 中有相同的范围吗?

c - 在 C 中读取字符串的详细信息?

C:字符串操作添加更多字符而不导致缓冲区溢出

c++ - 如何有效地找到具有相同第一个和最后一个字符的字符串中的子字符串数?

Android,找不到字符串资源

c - pthread 和 UDP

java - String.intern() 如何工作以及它如何影响字符串池?

python - 读取docx文件,识别和存储斜体文本

c - fscanf 只扫描我文件的第一个值