C - Better method for replacing

自古美人都是妖i 提交于 2019-12-11 07:58:56

问题


I'm looking to replace words from a file where words.txt contains "banana test apple" would output -> "banana Replaced! apple" The words it would be looking to replace would come as an argument to stdin ("test" in this case)

Not sure where my code is going wrong, and I'm also wondering if there's a better way to do it than get getchar() function, as I find it confusing to work with, and annoying as you cannot backup characters.

Any suggestions? Thanks

    $ ./a.exe test < words.txt


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

    int main(int argc, char** argv) { 
        int c = getchar();    
        int counter = 0;


        int i,index;
        for (i = 1; i < argc; i++){
            for (index = 0; index < strlen(argv[i]); index++){
                while (c == argv[i][index]){
                    counter++;
                    c = getchar();
                    index++;
                    if (counter == strlen(argv[i])){
                        printf("Replaced!");
                    }
                }
                printf("%c ",c);
                c = getchar();
                counter = 0;
            }
        }
        return (0);
    }

回答1:


I would do it as follows :

  1. read all the file into a buffer using fgets
  2. looking for the key work (test) using strstr
  3. replace it with your new string using strncpy
  4. write to file (or output to stdout) whatever you want to do



回答2:


You could use scanf to read in a word at a time:

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

int main(int argc, char *argv[])
{
    char wordbuffer[100];
    while (scanf("%99s", wordbuffer) == 1)
    {
        int replace = 0;
        for (int i = 1; i < argc && !replace; i++)
            if (strcmp(wordbuffer, argv[i]) == 0)
                replace = 1;

        if (replace)
            printf("Replaced! ");
        else
            printf("%s ", wordbuffer);
    }
}

If you are using a modern system that compliant with the latest POSIX specification, you can take advantage of the m assignment-allocation character, and have the appropriate amount of space allocated for you, so that you don't have to use some arbitrary maximum number of characters.

int main(int argc, char *argv[])
{
    char *wordbuffer;
    while (scanf("%ms", &wordbuffer) == 1)
    {
        int replace = 0;
        for (int i = 1; i < argc && !replace; i++)
            if (strcmp(wordbuffer, argv[i]) == 0)
                replace = 1;

        if (replace)
            printf("Replaced! ");
        else
            printf("%s ", wordbuffer);

        free(wordbuffer);
    }
}


来源:https://stackoverflow.com/questions/26171698/c-better-method-for-replacing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!