在您的代码中,将该行复制到输出文件,然后查找触发词。但目标是找到触发器并编辑字符串,然后才将该行写入输出文件。此外,为了编辑该行,您需要知道在哪里找到了触发器,因此您需要保存搜索的输出。
所以,而不是:
fprintf(fn, c); // writing charter from buffer "c" to empty file
if (strstr(c, trigger)) { // find triggered word
// I tried compare string which has a trigger-word
}
我们需要:
char *p = strstr(c, trigger);
if (p) {
// I tried compare string which has a trigger-word
}
fputs(c, fn); // writing charter from buffer "c" to empty file
所以现在我们找到了触发器,我们需要向后搜索以找到它之前的单词的结尾和开头。当我们找到它们时,我们需要创建一个点并插入编辑:
char *p = strstr(c, trigger);
if (p) {
// ok we found the trigger - now we need to search backwards
// to find the end and then the start of the word before
while (p>c && p[-1]==' ') p--; // find the end of the word
memmove(p+1, p, c+999 - p); // make a space for the ]
*p = ']';
while (p>c && p[-1]!=' ') p--; // find the start of the word
memmove(p+1, p, c+999 - p); // make a space for the [
*p = '[';
}
fputs(c, fn); // writing charter from buffer "c" to empty file
在这里试试:https ://www.onlinegdb.com/H18Tgy9xu
但是,如果字符串中有多个“o-clock”怎么办?像这样的东西:
我们十二点去墓地,提前六点吃晚饭吧!
在这种情况下,您需要循环直到找到所有这些:
这是最终代码:
#include <stdio.h>
#include <string.h>
int main() {
FILE * fp; //open exists file
FILE * fn; //open empty file
char c[1000]; // buffer
char trigger[] = "o'clock"; // the word before which the characters should be added
char name [] = "startFile.txt"; // name of source file
char secondName[] = "newFile.txt"; // name of output file
fp = fopen (name, "r"); // open only for reading
if (fp == NULL) { // testing on exists
printf ( "Error");
getchar ();
return 0;
}
fn = fopen(secondName, "w"); // open empty file for writing
if (fn == NULL) { // testing on create
printf ( "Error");
getchar ();
return 0;
}
while (fgets(c, 1000, fp)) { // scanning all string in the source
char *p = c; // we need to start searching at the beginning
do {
p = strstr(p+1, trigger); // find the next oclock after this one
if (p) {
// ok we found the trigger - now we need to search backwards
// to find the end and then the start of the word before
while (p>c && p[-1]==' ') p--; // find the end of the word
memmove(p+1, p, c+999 - p); // make a space for the ]
*p = ']';
while (p>c && p[-1]!=' ') p--; // find the start of the word
memmove(p+1, p, c+999 - p); // make a space for the [
*p = '[';
p = strstr(p, trigger); // find that same oclock again
// (we couldn't save the location because memmove has changed where it is)
}
} while (p); // as long as we found one, search again
fputs(c, fn); // writing charter from buffer "c" to empty file
}
fclose(fp); // closing file
fclose(fn);
return 0;
}
在这里试试:https ://onlinegdb.com/SJMrP15ld