繁体   English   中英

如何按字母顺序对句子中的每个单词进行排序?

[英]How do I Alphabetically sort each word in a sentence?

我需要按字母顺序对句子中的每个单词进行排序,同时将单词彼此分开。 我不允许使用 strtok() 函数。

示例输入: I would really appreciate some help

示例输出: I dlouw aellry aaceeipprt emos ehlp

我已经设法按字母顺序对整个字符串进行排序。这给了我一个输出: Iaaacdeeeeehillllmooppprrstuwy

我不确定是否应该将当前代码嵌套到一个循环中,每次有空间时都会重新开始。 或者,如果我需要将我的字符串读入一个二维数组并分别对每个单词进行排序。

我也不确定比较每个字符的值或计算字符串中每个字母的出现是否更有意义。 我有每个版本,它给了我上面显示的输出。

提前致谢。

版本比较字符:

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

int main () {

    char str[100];

    printf("Please type a sentence :\n");
    scanf("%[^\n]s", str);

    printf("\nAlphabetical order:\n:);

    char temp;

    int i, j;
    int n = strlen(str);

    for (i = 0; i < n-1; i++) {
        for (j = i+1; j < n; j++) {
            if (str[i] > str[j]) {
                temp = str[i];
                str[i] = str[j];
                str[j] = temp1;
            }
        }
    }

    printf(str);

    return 0;
}

每个字符的版本计数出现次数:

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

int main () {

  char ch, input[100], output[100];
  int no[26] = {0}, n, c, t, x;

  printf("Please type a sentence:\n");
  scanf("%s", input);

  n = strlen(input);

  for (c = 0; c < n; c++)
  {
    ch = input[c] - 'a';
    no[ch]++;
  }

  t = 0;

  for (ch = 'a'; ch <= 'z'; ch++)
  {
    x = ch - 'a';

    for (c = 0; c < no[x]; c++)
    {
      output[t] = ch;
      t++
    }
  }
  output[t]  = '\0';

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

  return 0;

}

std::sort将对您提供的任何序列进行排序。 例如

std::sort(str.begin(),str.begin()+5);
std::sort(str.begin()+6,str.end());
std::cout<<str;

应该输出Hello dlorw 如果您想区别对待大写字母,您可以放置​​自定义比较运算符。

现在你只需要遍历单词。 请不要随意混用 C++ 和 C。

标准库有足够的设施让您无需编写任何自己的循环。 看:

如何在 C++ 中标记字符串?

关于使用文字和

C++ 标准算法库

用于排序等。哦,您可能还想阅读迭代器。

使用fgets()读取用户输入。 在尝试使用输入之前验证成功。

char buffer[1024];
if (fgets(buffer, sizeof buffer, stdin)) {
  const char *s = buffer;

搜索字母。 使用isalpha()

  while (*s) {
    while (!isalpha((unsigned char)*s) && *s) {
      putchar(*s);
      s++;
    }
    const char *start = s;
    while (isalpha((unsigned char)*s)) {
      s++;
    }

使用qsort()排序并使用精度进行打印。 现在s不需要以空字符结尾。 避免使用sizeof(type)并使用sizeof *pointer因为它更容易正确编码、审查和维护。

    int len = s - start;
    qsort(start, len, sizeof *start, fcmp);
    printf("%.*s", len, start);
  }
}

fcmp()只是比较字符。 标准库倾向于将char的值视为转换为unsigned char

int fcmp(const void *va, const void *vb) {
  const unsigned char *a = va;
  const unsigned char *b = vb;
  return (*a > *b) - (*a < *b);
}

代码可以使用return a - b; . 以上是更惯用的,从不涉及int溢出(与那些具有CHAR_MAX > INT_MAX稀有机器不同)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM