c - 我的代码没有正确地将一个单词替换为另一个单词

标签 c string replace cpu-word

我刚刚用 c 编写了一个简单的代码,该代码应该从文件中提取文本并将一个单词替换为另一个单词。但是,我不知道为什么,但我的代码只是替换从第二个字母开始的单词。我究竟做错了什么? 这是我的代码:

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

 int main()
 {



FILE *f;

char sir[20];

if ((f=fopen("fis.txt","r"))==NULL)
{
    printf("Not ok");
    exit(1);
}
gets(sir);
fscanf(f, "%s",sir);

printf("Give the word you are looking for and the word to replace it with");
getchar();

char s1[10],s2[10];
gets(s1);
gets(s2);


char *p, aux[100];
while (p=strstr(sir,s1))

{
    strcpy(aux,p+strlen(s1));
    strcpy(p,s2);
    strcpy(p+strlen(s2),aux);
    puts(sir);


}


}

最佳答案

我发现你的方法有点太复杂了,只需移动指针就可以简单得多。这是一个粗略的(1)草图:

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

int main(void)
{
  /* Input file */
  FILE *f;
  /* Buffer for content of input-file */
  char sir[100] = { 0 };
  /* Temporary memory to hold the result */
  /* char tmp[100] = {0}; */
  /* Memory for the word to find and the one to replace */
  char s1[10], s2[10];
  /* Pointer to the occurrence of the word to replace */
  char *p;
  /* Pointer to sir, the memory holding the content of the file */
  char *c;

  if ((f = fopen("fis.txt", "r")) == NULL) {
    printf("Not ok");
    exit(EXIT_FAILURE);
  }
  /* Read content of file, leave room for the final `\0` */
  /* TODO: check return of fread() */
  fread(sir, 99, 1, f);

  printf("Give the word you are looking for and the word to replace it with: \n");
  /* TODO: check return of scanf() */
  /* HINT: you should read the two words separately. Ask for the word to find first,
   * read it and repeat that for the word to replace. */
  scanf("%9s %9s", s1, s2);
  /* Give user a change to stay in control. */
  printf("You are looking for %s and want it to be replaced with %s\n", s1, s2);

  /* We want to move through the input, we can do it quite comfortably with a pointer */
  c = sir;
  /* For every occurrence of the word to replace */
  while ((p = strstr(c, s1)) != NULL) {
    /* Print all characters up to the pointer p */
    /* TODO: change it to fill tmp instead. */
    /* HINT: I would use a pointer to tmp to do it but check the length! */
    while (c < p) {
      printf("%c", *c);
      c++;
    }
    /* Print the replacement / fill tmp */
    printf("%s", s2);
    /* Move the pointer to sir to the point in sir after the original word */
    c = p + strlen(s1);
  }
  /* Print / fill tmp with the rest of sir. Check the length if you use tmp! */
  printf("%s", c);
  /* Get outta here! */
  exit(EXIT_SUCCESS);
}

关于c - 我的代码没有正确地将一个单词替换为另一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54281647/

相关文章:

c - 对链表进行排序时出现段错误

我可以在解释这段代码时得到一些帮助吗?

javascript - 为什么我的字符串的一部分被省略了?

JavaScript 替换所有奇怪的行为

c - 当我们在txt文件中搜索单词时,我们如何在txt文件中着色

c - 为什么在反转字符串时不使用指向指针的指针?

c - 面试题-C中不使用strcat连接两个字符串

Javascript将字符串分成不同的变量

ios - 触摸 uitextField 时如何用 uitextView 替换 uitextField (swift 2)

python - 在 Pandas 数据框中填充一列字符串