首页 > 解决方案 > 用用户输入字符串替换提供的字符串?

问题描述

我将以这曾经有效的事实作为开头。我添加了一个打印语句(现在已经消失),它只是要求用户输入字符串。

输入是通过以下方法完成的:

./Project aa b

aa是要替换的代码,并且b将是替换用户输入中任何出现的字母的字母。

因此对于

./project Timmy Johhny
Timmy strolled through the park

输出将是

Johhny strolled through the park.

正如我所说,它确实有效,之后只是打印了空格。

我的代码如下所示:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * isMatch(char* os, char* ns, char* us){
        int i;
        int oslen, nslen, uslen;
        int it = 0;
        uslen = strlen(us);
        oslen = strlen(os);
        nslen = strlen(ns);
        for(i=0; i < uslen; i++){
                if(strstr(&us[i], os) == &us[i]){
                        it = it + 1;
                        i = i + oslen - 1;
                }
        }
        char *ans = malloc(uslen + nslen * it);
        int anslen = uslen + nslen * it;
        i = 0;
        while(*us){
                if(strstr(us, os) == us){
                        strcpy(&ans[i], ns);
                        i = i + nslen;
                        us = us + oslen;
                }
                else
                        ans[i++] = *us++;



        }
        return ans;                                                                                                                                                    
}


int main(int arg1, char * argp[]){

        char input[100];

        int i;
        char c;


        while(1){
                if(scanf("%c",&c)==EOF){
                        break;
                }
                if( (input[0]=c) != '\n'){
                        for(i=1;i<100;i++){
                                scanf("%c", &input[i]);
                                if(input[i] == '\n'){
                                        break;
                                }

//                            char *match = isMatch(argp[1],argp[2],&input[i]);
//                              printf("%s", match);
//                              free(match);


                        }
                        char *match = isMatch(argp[1],argp[2],&input[i]);
                        printf("%s", match);
                        free(match);

                }

        }
}
   

我只是犯了一个小错误,还是更大的错误。我试图将 printf 移入和移出 for 循环以及其他所有内容,只是得到了越来越奇怪的输出。

谢谢!

标签: arrayscstringuser-input

解决方案


推荐阅读