如何解决如何在 c 中编写一个函数 char* 返回按长度排序的单词?
编写一个函数,将字符串作为参数并返回其单词,首先按长度排序,然后按字母顺序排列在由 '^' 分隔的行 here is examples of output 字符串中将只有空格、制表符和字母数字字符。
相同大小的单词和 ^ 之间只有一个空格,否则。
单词是由空格/制表符或字符串的开头/结尾分隔的字符串部分。如果一个单词只有一个字母,它必须大写。
字母是集合[a-zA-Z]中的一个字符
这是我的代码,但它没有返回任何我认为在最后一个函数中有问题的....
#include <unistd.h>
#include <stdlib.h>
int is_upper(char c)
{
return c >= 'A' && c <= 'Z';
}
int my_lower(char c)
{
if (is_upper(c))
return c + 32;
return c;
}
int my_strlen(char *s)
{
int i = 0;
for (; s[i]; i++)
;
return i;
}
int my_is(char c)
{
return c == ' ' || c == '\t';
}
char *my_strsub(char *s,int start,int end)
{
char *res = malloc(end - start);
int i = 0;
while (start < end)
res[i++] = s[start++];
res[i] = 0;
return res;
}
int cmp_alpha(char *a,char *b)
{
while (*a && *b && *a == *b)
{
a++;
b++;
}
return my_lower(*a) <= my_lower(*b);
}
int cmp_len(char *a,char *b)
{
return my_strlen(a) <= my_strlen(b);
}
void my_sort(char *arr[],int n,int(*cmp)(char*,char*))
{
char *tmp;
for (int i = 0; i < n; i++)
for (int j = 0; j < n - 1; j++)
{
if ((*cmp)(arr[j],arr[j + 1]) == 0)
{
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
char* long(char *s)
{
int start = 0,idx = 0;
char *words[my_strlen(s) / 2 + 1];
for (int i = 0; s[i]; i++)
{
if (!my_is(s[i]) && i > 0 && my_is(s[i - 1]))
start = i;
if (my_is(s[i]) && i > 0 && !my_is(s[i - 1]))
words[idx++] = my_strsub(s,start,i);
if (!s[i + 1] && !my_is(s[i]))
words[idx++] = my_strsub(s,i + 1);
}
my_sort(words,idx,&cmp_alpha);
my_sort(words,&cmp_len);
char* res = malloc(100);
int pushed=0;
for (int i = 0; i < idx - 1; i++)
{
res[pushed]=*words[i];
if (my_strlen(&res[pushed]) < my_strlen(&res[pushed + 1]))
{
res[pushed]=res[94];
}
else
{
res[pushed]=res[32];
}
pushed++;
}
res[pushed]='\0';
return res;
}
int main()
{
long("Never take a gamble you are not prepared to lose");
return 0;
}
解决方法
除了 my_strsub
中的 off-by-one 分配错误外,分离和排序单词似乎工作得很好。只有这样,您才会将结果字符数组与字符指针数组混淆,例如。 G。使用 res[pushed]=*words[i]
您只将单词的第一个字符写入结果。 for
的最后一个 ord_alphlong
循环可能是:
if (idx)
for (int i = 0; ; )
{
char *word = words[i];
int lng = my_strlen(word);
if (100 < pushed+lng+1) exit(1); // too long
for (int i = 0; i < lng; ) res[pushed++] = word[i++];
if (++i == idx) break; // last word
res[pushed++] = lng < my_strlen(words[i]) ? '^' // other size
: ' '; // same size
}
当然,为了看到函数的结果,你必须以某种方式输出它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。