我需要按字母顺序对句子中的每个单词进行排序,同时保持单词彼此分开。我不允许使用 strtok() 函数。
示例输入:我非常感谢一些帮助
示例输出: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;
}
最佳答案
使用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
的罕见机器不同)。
关于c - 如何按字母顺序对句子中的每个单词进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55543409/