我正在打開并閱讀字典檔案并計算檔案中有多少單詞。然后我將每個單詞單獨存盤在一個字串陣列中。之后,我使用函式按長度和字母順序對單詞進行排序qsort()。現在,我正在嘗試訪問該表并計算有多少單詞具有相同的長度,但我在決定下一步應該如何進行時遇到了一些困難。到目前為止我寫的代碼是這樣的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR 100
/* Sorting the words by length and alphabtichal order,
being legnth priority number one */
int compare(const void *a, const void *b){
const char **str_a = (const char **)a;
const char **str_b = (const char **)b;
int len1 = strlen(*str_a);
int len2 = strlen(*str_b);
if (len1 < len2) return -1;
if (len1 > len2) return 1;
return strcmp(*str_a, *str_b);
}
int main (int argc, char *argv[]){
FILE *fp = NULL;
int i = 0, n_total_palavras = 0;
char str[MAX_STR];
int count = 0;
char **Words;
fp = fopen("words.dict", "r");
if (fp == NULL){
exit (0);
}
while (fscanf(fp,"%s",str) == 1){
n_total_palavras ;
}
Words = (char **)malloc(n_total_palavras * sizeof (char *));
if (Words == NULL){
exit(0);
}
for (i = 0; i < n_total_palavras; i ){
Words[i] = NULL;
}
rewind (fp);
while (fscanf(fp,"%s",str) == 1){
Words[count] = (char*)malloc((strlen(str) 1) * sizeof(char));
strcpy(Words[count], str);
count ;
}
qsort(Words, n_total_palavras, sizeof(Words[0]), compare);
/* for(i = 0; i < n_total_palavras; i ){
printf("%s\n", Words[i]);
}
*/
fclose(fp);
return 0;
}
我試圖獲得類似的東西:
4 letters words: 2018
5 letters words: 170
6 letters words: 10
(...)
關于我應該如何看待這個的任何想法?
uj5u.com熱心網友回復:
這是我的代碼實作我的建議。它讀取檔案一次,根據需要增加單詞串列。每次需要更多空間時,它分配的空間大約是以前的兩倍。
我稍微簡化了比較函式——但優化器可能已經接近我寫的東西了。
該代碼當前配置為不列印已排序的單詞串列。
/* SO 7400-7509 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR 100
/*
* Sorting the words first by length and then in alphabetical order
*/
static int compare(const void *a, const void *b)
{
const char *str_a = *(const char **)a;
const char *str_b = *(const char **)b;
int len1 = strlen(str_a);
int len2 = strlen(str_b);
if (len1 < len2)
return -1;
if (len1 > len2)
return 1;
return strcmp(str_a, str_b);
}
int main(int argc, char *argv[])
{
char str[MAX_STR];
char **words = 0;
size_t max_words = 0;
size_t num_words = 0;
const char *filename = "words.dict";
if (argc == 2)
filename = argv[1];
else if (argc > 2)
{
fprintf(stderr, "Usage: %s [filename]\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
fprintf(stderr, "%s: failed to open file '%s' for reading\n",
argv[0], filename);
exit(EXIT_FAILURE);
}
while (fscanf(fp, "
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/512708.html
標籤:C字符串数组
上一篇:如何在C中撰寫多個內核
