【问题标题】:How to permanently change a substring of an array? C programming如何永久更改数组的子字符串? C 编程
【发布时间】:2018-11-03 22:46:27
【问题描述】:

假设我有一个数组,其中包含以下表达式:

X1+B*3

然后我为用户提供选项,使其在 while 循环中运行:

int main(){
   char infix[50];
   strncpy(infix, argv[1], 50);
   infix[50] = '\0';

   int userInput;


   while (userInput != 7){

            printf("Please input a number.\n");
            scanf("%d", &userInput);

                    if (userInput == 1){
                            display(infix);
                    }
                    else if (userInput == 2){
                            numReplace(infix);
                    }
            }
}

选项 1 显示当前表达式,选项 2 更改表达式的值,使得 numReplace 包含:

char numReplace(char infix[50])
{
    char rep[50];
    char newstr[50];

    printf("Please enter the variable to be replaced\n");
    scanf("%s", rep);

    printf("Please enter the value to be placed\n");
    scanf("%s", newstr);

    char result[1000] = "";
    char *tmp;
    int len;
    char *k = infix;
    char *res = result;
    while (1)
    {
            tmp = strstr(k,rep);
            if (tmp == NULL)
                    break;
            len=tmp-k;
            tmp=tmp+strlen(rep);
            strncpy(res,k,len);
            strcat(res,newstr);
            res += len + strlen(newstr);
            k = k+len+strlen(rep);
    }
    if (!tmp)
    strcat(result,k);
    puts(result);

}

在进行打印测试后,函数 numReplace 确实起作用,如果我选择将变量 X1 替换为 2,则新表达式为

2+B*3

但是,当我让用户再次选择选项,并且用户选择选项 1,即显示选项时,表达式将恢复到其正常状态:

X1+B*3

有人可以帮助我,以便用户输入永久编辑表达式吗?谢谢!

【问题讨论】:

    标签: c string replace printing


    【解决方案1】:

    你总是在 while 调用numReplace(infix);。但是你永远无法改变中缀。在您的函数numReplace 上,您必须更改中缀,但您创建/更改结果。它是函数的局部变量。如果您直接更改中缀,则可以解决不止一次迭代的问题。

    最后尝试使用strcpy,将结果复制到中缀

    strcpy(infix, result);
    

    您需要确保 result 适合 infix,否则会导致缓冲区溢出。您可以分配相同的大小。

    【讨论】:

    • 我觉得解决方案非常简单,但我的代码仍然无法正常工作,我尝试用中缀替换结果变量,但我当然不认为这是解决方案。你能给我提供它的代码吗?
    • 非常感谢!我完全忘记了 strcpy 的存在
    猜你喜欢
    • 2010-12-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多