【问题标题】:Sort words in a string based on their vowel number根据元音编号对字符串中的单词进行排序
【发布时间】:2014-07-31 11:44:04
【问题描述】:

我必须用 C 语言编写一个程序,允许用户说出他们想在一个字符串中输入多少个单词,然后我必须根据它们的元音编号对这些单词进行排序(元音多的单词排在第一位,而最少的元音在最后 - 如果两个单词的元音数量相同,则按照它们出现的顺序保留它们)。例如:

string - "Aaaa Bbbbbbb B CD home Aaa BB A poke"

排序后的字符串——“Aaaa Aaa home poke A Bbbbbbb B CD BB”

我知道如何写第一部分,但对于排序部分我不知道。有人可以帮我吗?

编辑:目前我有这个代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#pragma warning (disable: 4996)

int main(){
    char string1[20], string2[100] = { '\0' };
    int N, i;
    do{
        printf("Enter the number of words you want to enter in the string: ");
        scanf("%d", &N);
        if (N < 2){
            printf("You must enter at least two words.\n");
            printf("Enter the number of words you want to enter in the string: ");
            scanf("%d", &N);
        }
    } while (N < 2);

    for (i = 0; i < N; i++){
        printf("Enter a word: ");
        scanf(" %[^\n]", string1);
        if (strlen(string2) == 0)
            strcpy(string2, string1);
        else {
            strcat(string2, " ");
            strcat(string2, string1);
        }
    }

    printf("%s\n", string2);

    return 0;
}

【问题讨论】:

  • 查找冒泡排序。它可以处理你想做的事情。
  • 使用标准库 qsort() 函数可以轻松进行排序。
  • 可能您的课程涵盖了排序算法,您应该使用其中之一。
  • @NicholasYoung - 任何稳定排序算法都可以,但鉴于这似乎是一个学习程序而不是生产程序,冒泡排序或插入排序都是合适的。
  • 我知道如何使用冒泡排序对整数数组进行排序,但我不知道如何根据元音编号对字符串中的单词进行排序。

标签: c string sorting


【解决方案1】:

您需要创建一个结构数组,其中包含指向单词的指针以及每个单词中元音的数量。比如:

struct vowelcnt {
    char *word;
    int numvowels;
}

然后对结构数组进行排序(基于numvowels 的降序。然后简单地循环输出word 的排序结构,这将为您提供按包含的元音数量排序的单词。希望对您有所帮助。

【讨论】:

  • 我还没有使用过结构数组,但我会尝试的。谢谢。
  • 需要注意保留单词出现的原始位置,否则,想法很可靠。
  • @XWind - 没有技巧。这与使用一维数组相同。如果您知道要处理的最大单词数,那么您可以直接声明您需要的结构数。例如。 struct vowelcnt vc[100];。然后,您将使用 dot 表示法访问结构成员,例如vc.word = wordpointer;vc.numvowels = x;。或者您可以声明多个指向 struct struct vowelcnt *vc[100]; 的指针在这里您需要使用 malloc 进行分配并使用 rt-arrow 符号进行访问,例如vc-&gt;word = wordpointer;
猜你喜欢
  • 2022-06-26
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 2014-10-29
相关资源
最近更新 更多