我的程序設計爲允許用戶輸入字符串,我的程序將輸出每個字母和單詞的出現次數。我的程序也按字母順序排列單詞。在字符串數組中排序字
我的問題是:我輸出單詞看到(第一unsorted)和他們的事件作爲表,並在我的表中,我不想重複。 求助
例如,如果單詞「to」被看到兩次,我只希望單詞「to」在我的表中只出現一次,輸出出現次數。
我該如何解決這個問題?另外,爲什麼我不能簡單地將string[i] == delim
設置爲適用於每個分隔符,而不必爲每個分隔符手動分配?
編輯:修正了我的輸出錯誤。但我怎樣才能設置條件string[i]
等於我的代碼中的任何分隔符,而不是僅僅爲空格鍵工作?例如,在我的輸出中,如果我輸入「你,你」,它會輸出「你,你」而不僅僅是「你」。我怎麼寫它,以便它消除逗號並將「你,你」比作一個單詞。
任何幫助表示讚賞。我的代碼如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char delim[] = ", . - !*()&^%$#@<> ? []{}\\/\"";
#define SIZE 1000
void occurrences(char s[], int count[]);
void lower(char s[]);
int main()
{
char string[SIZE], words[SIZE][SIZE], temp[SIZE];
int i = 0, j = 0, k = 0, n = 0, count;
int c = 0, cnt[26] = { 0 };
printf("Enter your input string:");
fgets(string, 256, stdin);
string[strlen(string) - 1] = '\0';
lower(string);
occurrences(string, cnt);
printf("Number of occurrences of each letter in the text: \n");
for (c = 0; c < 26; c++){
if (cnt[c] != 0){
printf("%c \t %d\n", c + 'a', cnt[c]);
}
}
/*extracting each and every string and copying to a different place */
while (string[i] != '\0')
{
if (string[i] == ' ')
{
words[j][k] = '\0';
k = 0;
j++;
}
else
{
words[j][k++] = string[i];
}
i++;
}
words[j][k] = '\0';
n = j;
printf("Unsorted Frequency:\n");
for (i = 0; i < n; i++)
{
strcpy(temp, words[i]);
for (j = i + 1; j <= n; j++)
{
if (strcmp(words[i], words[j]) == 0)
{
for (a = j; a <= n; a++)
strcpy(words[a], words[a + 1]);
n--;
}
} //inner for
}
i = 0;
/* find the frequency of each word */
while (i <= n) {
count = 1;
if (i != n) {
for (j = i + 1; j <= n; j++) {
if (strcmp(words[i], words[j]) == 0) {
count++;
}
}
}
/* count - indicates the frequecy of word[i] */
printf("%s\t%d\n", words[i], count);
/* skipping to the next word to process */
i = i + count;
}
printf("ALphabetical Order:\n");
for (i = 0; i < n; i++)
{
strcpy(temp, words[i]);
for (j = i + 1; j <= n; j++)
{
if (strcmp(words[i], words[j]) > 0)
{
strcpy(temp, words[j]);
strcpy(words[j], words[i]);
strcpy(words[i], temp);
}
}
}
i = 0;
while (i <= n) {
count = 1;
if (i != n) {
for (j = i + 1; j <= n; j++) {
if (strcmp(words[i], words[j]) == 0) {
count++;
}
}
}
printf("%s\n", words[i]);
i = i + count;
}
return 0;
}
void occurrences(char s[], int count[]){
int i = 0;
while (s[i] != '\0'){
if (s[i] >= 'a' && s[i] <= 'z')
count[s[i] - 'a']++;
i++;
}
}
void lower(char s[]){
int i = 0;
while (s[i] != '\0'){
if (s[i] >= 'A' && s[i] <= 'Z'){
s[i] = (s[i] - 'A') + 'a';
}
i++;
}
}
您似乎誤解了一些語法,或者犯了一個簡單的錯誤:)'words [i] == NULL;'不做任何聲明。你將'words'中的'i'與'NULL'進行比較,'=='是相等運算符。該聲明甚至可能被編譯器優化掉。它在語法上有效,但什麼都不做,因爲你不會對結果做任何事情。沒有看過代碼的其餘部分,但你很可能希望'='(賦值) – Skurmedel
lower()被破壞:用_s [i] =(s [s]替換_s [i] = s [i] + 32_我] - 'A')+'a'_ –
謝謝我修復了Craig。 – Benny