我真的用这种功能打了墙。我需要创建一个从字符串返回字符的函数。
用户可以输入任意数字,我需要在字符串中找到char,其中出现的总数是用户指定的数字。
有人知道如何用C语言完成它?
答案 0 :(得分:0)
#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;
}