如何使用C来取字符串并按字母顺序排列单词

时间:2014-10-19 13:54:48

标签: c

我被困住了。我有相当大的编程任务,大部分看起来都很简单,我坚持的部分是将一串文本分成一个数组中的单个单词,然后按字母顺序对它们进行排序。

E.g。如果字符串包含以下内容:"我被卡住了。请帮我堆叠交换"它将保存数组中的单词并按以下顺序输出:

am
exchange
help
i
me
please
stack
stuck
你能帮忙吗?

编辑:这是我到目前为止所拥有的:

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

int main()
{
    char str[] = "This is a test String, anything else? lol";
    char *hhh;

    int i;
    for(i=0;str[i];i++){
        str[i]=tolower(str[i]); //Converts the string to lower case
    }

    //Breaks the string into separate words based on spaces and some
    //punctuation (Anything which signals the end of a word)
    hhh = strtok(str," ,.-:;?!");

    while(hhh != NULL){
        printf("%s \n",hhh);
        hhh = strtok(NULL, " ,.-:;?!");
    }

}

正如您所看到的,我已将单词转换为小写r并且我可以输出它们但我不知道如何按字母顺序对它们进行排序。看看泡沫分类,我理解它,但我不明白如何使用它来完成我需要的。

2 个答案:

答案 0 :(得分:3)

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

int cmp(const void *a, const void *b){
    return strcmp(*(const char **)a, *(const char **)b);
}

int main(){
    char str[] = "This is a test String, anything else? lol";
    char *word, *words[strlen(str)/2+1];
    int i, n;

    for(i=0;str[i];i++){
        str[i]=tolower(str[i]);
    }

    i=0;
    word = strtok(str, " ,.-:;?!");

    while(word != NULL){
        words[i++] = word;
        word = strtok(NULL, " ,.-:;?!");
    }

    n = i;
    qsort(words, n, sizeof(*words), cmp);

    for(i=0; i<n; ++i)
        puts(words[i]);

    return 0;
}

答案 1 :(得分:-2)

我的代码很漂亮&#34;手册&#34;这意味着我不会使用strtoktolower之类的内容。我自己手动循环一切。如果您不喜欢这样,只需用这些功能替换相应的部件即可。你走了:

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

#define _WLEN   32  // maximum length of each word
#define _NWORDS 256 // maximum number of words in the sentence

void word_swap(char** w1, char** w2);

int main(int argc, const char * argv[]) {
    char* sentence      = "The quick brown fox jumps over the lazy dog."; // the sentence

    char to_ignore[10]  = ".,-\"'!?()";             // characters that are ignored
    char words[_NWORDS][_WLEN];                     // words will be stored here
    int i, j, k=0, l=0, word_count, swapped=0;      // some variables that will be needed

    /* First we loop through the sentence to separate the words */
    for (i=0; i<_NWORDS*_WLEN; i++) {
        /* If we reach the end of the sentence, finish up the last word with '\0' and quit the loop */
        if (*(sentence+i) == '\0') {
            words[k][l] = '\0';
            word_count = k+1;
            break;
        }
        /* Check if the current character is one that we want to ignore. If so, skip to the next character. */
        for (j=0; j<10; j++) {
            if (to_ignore[j] == *(sentence+i)) goto END_FOR;
        }
        /* If the current character is not a space, add it to a word */
        if (*(sentence+i) != ' ') {
            words[k][l] = *(sentence+i);
            l++;
        }
        /* ... if it is a space, finish the current word with '\0' and move to the next word */
        else {
            words[k][l] = '\0';
            k++;
            l=0;
        }
    END_FOR:;
    }

    /* Convert everything to lowercase so it's easy to sort the words */
    for (i=0; i<word_count; i++) {
        for (j=0; j<_WLEN; j++) {
            if (words[i][j] == '\0') break;
            /* If the letter is uppercase (ASCII codes 65-90) then add 32 to it, which is the lowercase variant */
            if (words[i][j] >= 65 && words[i][j] <= 90) words[i][j] += 32;
        }
    }

    /* Bubble sort the words in alphabetical order */
    do {
        for (i=0; i<word_count-1; i++) {
            if (strcmp(words[i], words[i+1]) > 0) {
                word_swap(&words[i], &words[i+1]);
                swapped = 1;
                break;
            } else swapped = 0;
        }
    } while (swapped != 0);

    /* Print the words on the screen */
    for (i=0; i<word_count; i++) printf("%s\n", words[i]);
}

void word_swap(char** w1, char** w2) {
    char tmp[_WLEN];
    memcpy(&tmp, w1, _WLEN);
    memcpy(w1, w2, _WLEN);
    memcpy(w2, &tmp, _WLEN);
}