c-如何按字母顺序排列字符串并返回指向已排序字符数组的指针



具体来说,我正在处理的问题是"定义一个名为sortString的函数,它需要一个字符数组,并返回一个指向字符数组的指针。该函数按字母顺序对字符串中的字符进行排序,按此顺序存储它们,并返回指向此排序字符数组的指标。字符数组可能包含空格和标点符号。排序时,空格和标点应被忽略l字母字符应改为小写,以便排序和输出。">

我在CLion中尝试了代码,但当我运行它时,它唯一打印的就是输入一个按字母顺序排列的字符串。可能是什么问题?我在下面复制了我的代码。

char sortString(char *characters) {
int i = 0;
int j = 0;
int lengthofstring;
char *throwaway;
char *newabcorder;
char anotherthrowaway;
lengthofstring = strlen(characters);
newabcorder = (char*)malloc(lengthofstring+1);
printf("Enter a string you want alphabetized: n");
throwaway = characters;
for ( anotherthrowaway = 'a' ; anotherthrowaway <= 'z' ; anotherthrowaway++ ) {
for ( i = 0 ; i < lengthofstring ; i++ ) {
if ( *throwaway == anotherthrowaway ) {
*(newabcorder+j) = *throwaway;
j++;
}
throwaway++;
}
throwaway = characters;
}
*(newabcorder+j) = '';
strcpy(characters, newabcorder);
free(newabcorder);
return *newabcorder;
}

您的代码存在多个问题:

  • throwaway=characters不会复制您的字符串,带有等号的字符串是相同的指针(两者在您的电脑内存中是相同的,因此您不能只编辑其中一个(。为了复制字符指针,您必须使用strcpy(dest,src(
  • 您返回了一个char,并且您的文本表示您希望返回一个字符串(char*(
  • 我不知道你想打印出什么,但由于你只有一行带有打印功能,这应该很清楚
  • 如果你想返回指针,不要释放它,而是释放所有其他指针

作为你应该学习的东西,我写了一个你可以建立的基础。也许这不是最优雅的方式,但我相信这是你发现错误的最好方式。

排序应该有效,但不应该返回值,而是将其存储在作为参数获得的char*中。

此外,你还需要对双关语和空格进行整理。

以下是基础:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *sortString(char *characters)
{
int i = 0;
int j = 0;
char anotherthrowaway;
int lengthofstring = strlen(characters);
char * newabcorder = (char *)malloc(lengthofstring + 1);
memset(newabcorder, '', lengthofstring+1);
char * throwaway = (char *)malloc(lengthofstring + 1);
strcpy(throwaway, characters);
for (anotherthrowaway = 'a'; anotherthrowaway <= 'z'; anotherthrowaway++)
{
for (i = 0; i < lengthofstring; i++)
{
if (*(throwaway+i) == anotherthrowaway)
{
*(newabcorder + j) = anotherthrowaway;
j++;
}
}
}
free(throwaway);
return newabcorder;
}
int main(){
printf("%sn", sortString("bcdajktzy"));
return 0;
}

首先,您写道函数必须返回一个指针值,但您的返回类型只是char,请将其更改为char*sortString

第二,在返回内存之前释放内存,意味着不返回任何内容,删除这一行。您需要在从sortString接收abcorder的主函数中声明一个指针变量,这是您在程序结束时释放的变量。

第三,您需要返回指针的地址,而不是指针变量,将其从*newaborder更改为return newaborder

固定功能:

char* sortString(char *characters) {
int i = 0;
int j = 0;
int lengthofstring;
char *throwaway;
char *newabcorder;
char anotherthrowaway;
lengthofstring = strlen(characters);
newabcorder = (char*)malloc(lengthofstring + 1);
printf("Enter a string you want alphabetized: n");
throwaway = characters;
for (anotherthrowaway = 'a'; anotherthrowaway <= 'z'; anotherthrowaway++) {
for (i = 0; i < lengthofstring; i++) {
if (*throwaway == anotherthrowaway) {
*(newabcorder + j) = *throwaway;
j++;
}
throwaway++;
}
throwaway = characters;
}
*(newabcorder + j) = '';
strcpy(characters, newabcorder);
return newabcorder;
}

主要功能:

int main() {
char str[50], *ptr;
fgets(str, 49, stdin);
ptr = sortString(str);
printf("%s n", ptr);
free(ptr);
}

最新更新