c - 从字符串中返回字符的函数,其中出现的字符是用户定义的

标签 c string

我对这种功能确实碰壁了。我需要创建一个从字符串返回字符的函数。

用户可以输入任何数字,我需要在字符串中查找字符,其中出现的总次数是用户指定的数字。

有人知道用C语言怎么实现吗?

最佳答案

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

int cmp(const void *a, const void *b){
    unsigned char ac = *(unsigned char *)a;
    unsigned char bc = *(unsigned char *)b;
    return ac < bc ? -1 : ac > bc;
}

char *func(const char *str, size_t n){
    size_t len = strlen(str);
    char *dup = malloc(len + 1);
    char temp[len + 1];//[256]

    strcpy(dup, str);
    qsort(dup, len, sizeof(*dup), cmp);

    char *p = dup;
    size_t i = 0;
    while(*p){
        char aChar[] = {*p, 0};
        len = strspn(p, aChar);
        if(len == n){
            temp[i++] = *p;
        }
        p += len;
    }
    temp[i] = 0;
    strcpy(dup, temp);
    return dup;
}

int main(void){
    char *occurs = func("111abcddaaa", 1);

    for(char *p = occurs; *p; ++p){
        printf("%c\n", *p);
    }

    free(occurs);

    return 0;
}

关于c - 从字符串中返回字符的函数,其中出现的字符是用户定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32910720/

相关文章:

python - 为什么当我使用 beautifulsoup 抓取 HTML 中的字符串时它们不起作用

javascript - 使用 split/join 将字符串替换为数组

c - 理解一个函数。 pcap 和 BPF

ios - 如何在 Swift 中将 Int 转换为十六进制字符串

c++ - 有没有更有效的方法来获取以字节为单位的 32 位整数的长度?

c - 在 yyparse() 调用时执行操作?

python - 转换列表中的字符串

java - 在字符串中搜索停用词

c - 如何在 Linux 上设置串口中断?

c - 为什么 fprintf()/fscanf()/printf() 在我的 Dec-to-Binary 程序中显示错误的输出,而 printf() 和 sscanf() 工作正常?