本题实现,输入一个包含空格的多单词字符串,单词与单词之间用1个或多个空格分隔。请将字符串中用空格分隔的单词排序后在屏幕上输出来。 要求用指针完成函数中各参数的传递与访问,自定义函数头和函数体中不得出现数组下标形式的表示法。
函数接口定义:
intsplit_sort(char *str,char **pStr);
函数对字符串中的单词进行分割,并按字典顺序输出排序后的单词,函数返回字符串中单词的数目。str用于接收实参字符串,pStr用于存放分割后的各单词对应字符串的首地址。下面函数的定义部分框架与花括号部分已经给出了,只需给出函数{...}之中的部分。
裁判测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
#include<stdio.h>intsplit_sort(char *str,char **pStr);
intmain(void){
char arr[101]={0},*pX[50];
char **p=pX;
int wordNum;
gets(arr);
wordNum=split_sort(arr,p);
for(;p<pX+wordNum;p++)
printf("%s ",*p);
return0;
}
intsplit_sort(char *str, char **pStr){
/* 请在这里填写答案 */}
输入样例:
在这里给出一组输入。例如:
china america japan egypt germany
输出样例:
在这里给出相应的输出。例如:
america china egypt germany japan
代码长度限制16 KB
时间限制400 ms
内存限制64 MB
int split_sort(char *str, char **pStr)
{
int i,j,len,cou=0;
for(i=0;*(str+i)!='\0';i++)//一一对应
{
if(*(str+i)!=' '&&i==0)//首单词
{
*(pStr+cou)=str+i;
cou++;
}
else if(*(str+i)!=' '&&*(str+i-1)==' ')
{
*(pStr+cou)=str+i;
cou++;
}
if(*(str+i-1)==' '&&*(str+i-2)!=' ')//于空格处截断
{
*(str+i-1)='\0';
}
}
char *tmp=NULL;
for(i=0;i<cou;i++)
for(j=i+1;j<cou;j++)
{
if(cmpStr(*(pStr+i),*(pStr+j))>0)
{
tmp=*(pStr+i);
*(pStr+i)=*(pStr+j);
*(pStr+j)=tmp;
}
}
return cou;
}
int cmpStr(char *str1,char *str2)//str1>str2为真
{
int i;
for(i=0;;i++)
{
if(*(str1+i)>*(str2+i)) return 1;
else if(*(str1+i)<*(str2+i)) return 0;
if(*(str1+i)=='\0') return 0;
else if(*(str2+i)=='\0') return 1;
}
}
Dev c++ (gcc 4.9.2)正常运行无错误