簡體   English   中英

在strstr()中為匹配的子字符串着色

[英]Coloring matching substring in strstr()

這里是C的初學者。

我知道strstr()可用於查找字符串是否包含某個子字符串,並且printf()可以顯示彩色輸出(如此處所述: stdlib和C中的彩色輸出 )。

我試圖找出的是一種僅對字符串的匹配部分進行着色的簡單方法(例如grep ),因為strstr()從匹配返回行的整個部分。 或者,我可以打印整個匹配的行,但最終將整個行着色。

假設出於說明目的,粗體=着色,那么在搜索子字符串大象時我想要的結果是:

這是大象的象牙

printf +為strstr()着色可以得到:

象牙

當然,printf +為整個匹配的行着色會給出:

這是大象的象牙

預先感謝您的幫助。

最簡單的解決方案是將打印過程分為三部分。 如果strstr返回非NULL結果,請打印從初始字符串開始直到到達strstr結果的字符數。 然后為strstr結果着色,直到“ needle”的長度匹配為止。 然后打印干草堆中未着色的其余部分:

const char *color_start, *color_end;

print_head = haystack;
color_start = strstr (haystack, needle);
color_end = color_start + strlen (needle) - 1;

while (*print_head) {
    if (print_head == color_start) { /* init color change */ }
    else if (print_head == color_end) { /* revert color change */ }
    putchar (*print_head++);
}

一個更有效的版本是:

const char *color_start, *color_end;

print_head = haystack;
color_start = strstr (haystack, needle);
color_end = color_start + strlen (needle) - 1;

while (print_head < color_start)
    putchar (*print_head++);
/* init color change */
while (print_head <= color_end)
    putchar (*print_head++);
/* revert color change */
while (*print_head)
    putchar (*print_head++);

它效率更高,因為它在每個循環中僅測試一個條件,而不是每個循環中最多測試三個條件。

這是因為strstr返回一個指針中第一次出現的needlehaystack ,從手動

NAME

   strstr, strcasestr - locate a substring

SYNOPSIS

   #include <string.h>

   char *strstr(const char *haystack, const char *needle);

   #define _GNU_SOURCE         /* See feature_test_macros(7) */

   #include <string.h>

   char *strcasestr(const char *haystack, const char *needle);

DESCRIPTION 

   The strstr() function finds the first occurrence of the substring
   needle in the string haystack.  The terminating null bytes ('\0') are
   not compared.

   The strcasestr() function is like strstr(), but ignores the case of
   both arguments.

RETURN VALUE

   These functions return a pointer to the beginning of the located
   substring, or NULL if the substring is not found.

因此這是正確的輸出,如果要得到該結果,則必須使用strtok

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM