问题代码
使用知道数组的元素个数,使用for循环能够得到成功遍历。需要解决指针越界问题,是不是需要将保存单词表的数据结构改成链表形式才能使用指针进行自增加
#include<stdio.h>
#include<stdlib.h>
int countCharacters(char ** words, int wordsSize, char * chars);
void main(){
//使用数组的形式保存的字符串数组 -- 是不是自己可以设计一个链表进行保存
char *arr[] = { "attach", "excuse", "communicate" };
char *chars = "abcattchsexu";
int length = countCharacters(arr, 3, chars);
printf("%d", length);
system("pause");;
}
int countCharacters(char ** words, int wordsSize, char * chars){
int *num = (int*)malloc(sizeof(int)* 26);//用来统计字符串中各个元素出现的次数
for (int t = 0; t < 26; t++){
num[t] = 0;
}
while (*chars != '\0'){
num[*chars - 'a']++;
chars++;
}
int i = 0;//遍历单词表用
int length = 0;//统计符合要求的所有单词的字母数
while (*words != NULL){
int *arr = (int*)malloc(sizeof(int)* 26);//重置使用过的字母表
for (int i = 0; i < 26; i++){
arr[i] = num[i];
}
int b = 0;
int middlelength = 0;//是否符合要求的标志
char *second = *words;
while (*second != '\0'){ //统计单个单词
// second = (char)malloc(sizeof(char));
arr[*second - 'a']--;
printf("%c", *second);
if (arr[*second - 'a'] < 0){
b = 1;
break;
}
middlelength++;
second++;
}
if (b == 0){
length = length + middlelength;
}
b = 0; middlelength = 0;//将统计数值重置为0
words++;
}
return length;
}