C语言 如何处理参数数目可变的函数?

yvfmudvl  于 2023-03-28  发布在  其他
关注(0)|答案(1)|浏览(127)

我需要创建一个函数,输出给定字符串中给定字母重复三次或更多次的所有单词,而不使用<stdarg>
我已经尝试了下面的代码,但有些东西出错了,你能告诉我,请,如何解决这个问题?该程序以某种方式工作,但不完全正确,所以我想,我可以去没有宏.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>

int count_char(char* str, char c) {
    int count = 0;
    c = 'o';
    for (int i = 0; i < strlen(str); i++) {
        if (str[i] == c) {
            count++;
        }
    }
    return count;
}

void print_words(unsigned k, char* str, ...) {
    char* word;
    char* p;
    int i;
    const char* delim = " ,.;:!?\t\n\r\f\v";
    for (i = 0, p = str; i < k; p++) {
        word = strtok(p, delim);
        while (word != NULL) {
            for (int i = 0; i < strlen(word); i++) {
                int char_count = count_char(word, word[i]);
                if (char_count >= 3) {
                    printf("Words with repeated letter: %s\n", word);
                    break;
                }
            }
            word = strtok(NULL, " ");
          
        }
    }

}

int main() {
        char str1[] = "This is a sampooole sentenceoooo.";
        char str2[] = "Another sentence, with more woooords.";
        print_words(2, str1, str2);
        return 0;
}

这是我得到的输出:

Words with repeated letter: sampooole
    Words with repeated letter: sentenceoooo.
    Words with repeated letter: sampooole
    Words with repeated letter: ampooole
    Words with repeated letter: mpooole
    Words with repeated letter: pooole
    Words with repeated letter: ooole
    Words with repeated letter: sentenceoooo
    Words with repeated letter: entenceoooo
    Words with repeated letter: ntenceoooo
    Words with repeated letter: tenceoooo
    Words with repeated letter: enceoooo
    Words with repeated letter: nceoooo
    Words with repeated letter: ceoooo
    Words with repeated letter: eoooo
    Words with repeated letter: oooo
    Words with repeated letter: ooo
    Words with repeated letter: woooords.
    Words with repeated letter: woooords
    Words with repeated letter: oooords
    Words with repeated letter: ooords
9udxz4iz

9udxz4iz1#

看起来问题在于你如何在print_words函数中使用strtok。尝试使用输入字符串的副本,然后对副本进行标记,因为strtok修改了原始字符串,可能会导致损坏。尝试将print_words函数替换为以下内容:

void print_words(unsigned k, char* str, ...) {
    char* word;
    char* p;
    int i;
    const char* delim = " ,.;:!?\t\n\r\f\v";
    char *str_cpy = strdup(str);             // Copied string here
    for (i = 0, p = str; i < k; p++) {
        word = strtok(str_cpy, delim);       // Strtok copied string
        while (word != NULL) {
            for (int i = 0; i < strlen(word); i++) {
                int char_count = count_char(word, word[i]);
                if (char_count >= 3) {
                    printf("Words with repeated letter: %s\n", word);
                    break;
                }
            }
            word = strtok(NULL, delim);      
          
        }
    }
    free(str_cpy);
}

相关问题