打印一个单词,替换该单词,然后打印字符串的其余部分(C)

打印一个单词,替换该单词,然后打印字符串的其余部分(C),c,loops,substring,C,Loops,Substring,我有很多麻烦打印到字符串,然后替换单词,然后打印字符串的其余部分。我想用\e[7m word\e[0m替换“word”变量。我尝试使用strcasestr到达word在字符串中的位置,它返回一个从字符串开始的指针。我的问题是如何使用此指针打印字符串,直到该点,用\e[7m word\e[0m替换该单词,然后打印字符串的其余部分 struct node *ptr; int count = 0; char* filecheck = ""; char* tester = ""; cha

我有很多麻烦打印到字符串,然后替换单词,然后打印字符串的其余部分。我想用\e[7m word\e[0m替换“word”变量。我尝试使用strcasestr到达word在字符串中的位置,它返回一个从字符串开始的指针。我的问题是如何使用此指针打印字符串,直到该点,用\e[7m word\e[0m替换该单词,然后打印字符串的其余部分

        struct node *ptr;
int count = 0;
char* filecheck = "";
char* tester = "";
char* pch = "";
char str[1024];
int i; 
int j;
int charcount = 0;   

                int counter = 1;
                FILE *fp = fopen(ptr->fileName, "r");
                char line [ 1024 ]; /* or other suitable maximum line size */
                int counter = 1;
                while ( fgets ( line, sizeof line, fp ) != NULL ) /* read a line */{
                    //print the line
                     printf("\e[7m %s \e[0m", word);
                     printf("%s", line);

}

word
之后打印部件很容易:只需从字符
strlen(word)
word开始后的字符开始即可。打印替换项很简单(除非您需要计算替换项,您没有说明如何做)


如果
tester
中没有字符串常量,您可以将
*pch
设置为0,在
word
开头终止字符串,只需打印
tester
(然后将删除的字符放回原处)。相反,您可以将要打印的
tester
部分复制到一个字符数组中,然后打印出来。

这是一种简单的方法

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

int main(int argc, char **argv)
{
    char *tester = "Hello my name is Rocky the polar bear";
    char *pch    = NULL;
    char *word   = "the";

    pch = strcasestr(tester, word);
    if (pch != NULL)
    {
        size_t length;

        /* this will give the difference between the pointers */
        length = pch - tester;
        /* write to stdout from the start of the string just 'length' bytes */
        fwrite(tester, 1, length, stdout);
        /* write the word you want to substitute */
        printf("\033[7m%s\033[0m", word);
        /* pch is pointing to the start of 'word' in the string, advance to it's end */
        pch += strlen(word);
        /* print the rest of the string */ 
        printf("%s", pch);
    }

    return 0;
}
#包括
#包括
#包括
int main(int argc,字符**argv)
{
char*tester=“你好,我的名字是北极熊洛奇”;
char*pch=NULL;
char*word=“the”;
pch=strcasestr(测试仪,字);
如果(pch!=NULL)
{
尺寸与长度;
/*这将给出指针之间的差异*/
长度=pch-测试仪;
/*从字符串的开头写入stdout,只需“length”字节*/
F写入(测试仪,1,长度,标准输出);
/*写下你想替换的单词*/
printf(“\033[7m%s\033[0m”,字);
/*pch指向字符串中“word”的开头,前进到它的结尾*/
pch+=strlen(字);
/*打印字符串的其余部分*/
printf(“%s”,pch);
}
返回0;
}

“循环”?什么循环?你初始化
测试仪
,然后用
替换该值,但从不向我们展示
是什么。我的代码中的实现是一个循环,但我认为人们在没有循环的情况下做这件事会更容易,所以我认为它的大纲是一个文件中的fgets行,为方便起见,假设测试仪是测试仪,我将删除tester=Line,那么您为什么要为它保留标记?您已经将代码缩减到毫无意义的程度。如果您对代码为什么不起作用(或者为什么出错)有疑问,发布您的实际代码。否则,您将浪费您的时间和我们的时间。我的返回一堆unicode,我无法让它返回单词的开头,但我可以让其他一切正常工作