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

时间:2015-02-20 01:38:38

标签: c loops substring

我在打印字符串时遇到了很多麻烦,然后更换了字然后打印了字符串的其余部分。我想用\ e [7m word \ e [0m]替换“word”变量。我尝试使用strcasestr来到字符串中的单词,并返回一个从字符串开始的指针。我的问题是我如何使用这个指针打印到该点的字符串,用\ 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);

}

2 个答案:

答案 0 :(得分:2)

这是一种简单的方法

#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;
}

答案 1 :(得分:1)

word之后轻松打印部件:只需在strlen(word)开始后的字符word字符处开始。打印替换是微不足道的(除非你需要计算替换,你没有说明如何做)。

将部分留在word之前。如果tester中没有字符串常量,则可以将*pch设置为0,在word开头处终止字符串,然后只打印tester(然后把你擦掉的角色放回去)。相反,您可以将要打印的tester部分复制到字符数组中,然后打印出来。