【问题标题】:Adjust output based on the count of a substring within a string in a 2d char array根据二维字符数组中字符串中子字符串的计数调整输出
【发布时间】:2020-05-31 08:32:39
【问题描述】:

我正在从文件中读取一堆行并尝试打印包含特定关键字集的每一行。现在我的代码只查找一行中第一次出现的关键字,如果找到,它将打印该关键字和该行及其行号。但我正在努力做到这一点,如果该行包含不止一次出现的关键字,那么在打印输出中,行号旁边应该有一个星号。我尝试了许多不同的方法,但似乎没有任何效果。这是我的代码:

for(i = 0; i < wordCount_keyword; i++) {
    for(j = 0; j <= lineCount; j++) {
        if(strstr(inputLines[j], keywords[i]) != NULL) {
            printf("%-*s %s (%d)\n", max_length + 1, keywords_upper[i], inputLines[j], j+1);
        }
    }
}

这是我当前的输出:

CAT       the fish a dog cat dog rabbit (1)
CAT       the fish and cat  (2)
DOG       the fish a dog cat dog rabbit (1)
ELEPHANT  a rabbit or elephant (3)
FISH      the fish a dog cat dog rabbit (1)
FISH      the fish and cat  (2)
RABBIT    the fish a dog cat dog rabbit (1)
RABBIT    a rabbit or elephant (3)

这是我想要的理想正确输出:

CAT       the fish a dog cat dog rabbit (1)
CAT       the fish and cat  (2)
DOG       the fish a dog cat dog rabbit (1*)
ELEPHANT  a rabbit or elephant (3)
FISH      the fish a dog cat dog rabbit (1)
FISH      the fish and cat  (2)
RABBIT    the fish a dog cat dog rabbit (1)
RABBIT    a rabbit or elephant (3)

请注意区别在于第 3 行末尾括号中的 1 旁边的星号。 这样做的正确方法是什么?

【问题讨论】:

    标签: c arrays string char printf


    【解决方案1】:

    由于 c 中没有内置函数来计算字符串中某个单词的出现次数,因此您需要编写一个。假设函数的定义是“getWordOccurances(char * str, char * toSearch)”。那么下面的代码就可以解决你的问题了。

    for(i = 0; i < wordCount_keyword; i++) {
       for(j = 0; j <= lineCount; j++) {
           int count = getWordOccurances(inputLines[j], keywords[i]);
           if(count > 0) {
               printf("%-*s %s (%d", max_length + 1, keywords_upper[i], inputLines[j], j+1);
               if(count > 1) printf("*)\n");
               else printf(")\n");
           }
       }
    }
    

    getWordOccurances(char * str, char * toSearch) 函数可能如下所示:

    int countOccurrences(char * str, char * toSearch){
        int i, j, found, count;
        int stringLen, searchLen;
    
        stringLen = strlen(str);      // length of string
        searchLen = strlen(toSearch); // length of word to be searched
    
        count = 0;
    
        for(i=0; i <= stringLen-searchLen; i++) {
            /* Match word with string */
            found = 1;
            for(j=0; j<searchLen; j++) {
                if(str[i + j] != toSearch[j]) {
                    found = 0;
                    break;
                }
            }
    
            if(found == 1) count++;
        }
    
        return count;
    }
    

    如果您不了解程序的任何部分,请告诉我。编码愉快!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2021-06-12
      • 2021-01-24
      • 2015-05-22
      • 2023-03-14
      • 2016-05-06
      • 1970-01-01
      相关资源
      最近更新 更多