【发布时间】:2021-06-24 20:11:48
【问题描述】:
编写一个函数,它接受一个字符串作为参数,并返回它的单词,首先按长度排序,然后按字母顺序排列在由 '^' 分隔的行 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, start, i + 1);
}
my_sort(words, idx, &cmp_alpha);
my_sort(words, idx, &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;
}
【问题讨论】:
-
你说的每一行是什么意思?
-
示例不注意要求如果单词只有一个字母,则必须大写。
-
@Armali 它是写在任务中的,我认为这是他们的错误(他们考虑的是'\n'符号,而不是'^')我知道如何使用 void ord_alphlong 和 putstr 使其工作函数,但需要使用带有返回的 char* 函数......
-
my_strsub分配的内存不足。 -
你不使用标准的字符串函数吗?
标签: c function sorting char malloc