本题实现,输入一个包含空格的多单词字符串,单词与单词之间用1个或多个空格分隔。请将字符串中用空格分隔的单词排序后在屏幕上输出来。 要求用指针完成函数中各参数的传递与访问,自定义函数头和函数体中不得出现数组下标形式的表示法。
函数接口定义
int split_sort(char *str,char **pStr);
函数对字符串中的单词进行分割,并按字典顺序输出排序后的单词,函数返回字符串中单词的数目。str用于接收实参字符串,pStr用于存放分割后的各单词对应字符串的首地址。下面函数的定义部分框架与花括号部分已经给出了,只需给出函数{}之中的部分。
裁判测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
#include<stdio.h>
int split_sort(char *str,char **pStr);
int main(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);
return 0;
}
int split_sort(char *str, char *pStr)
{
/ 请在这里填写答案 */
}
输入样例:
在这里给出一组输入。例如:
china america japan egypt germany
输出样例:
在这里给出相应的输出。例如:
america china egypt germany japan
int split_sort(char* str, char** pStr);
int main(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);
return 0;
}
int split_sort(char* str, char** pStr)
{
char* s = str, **p = pStr;
for (; *s != '\0'; s++) {
if (*s == ' ' && *(s + 1) != ' ') {
*p = str;
p++;
*s = '\0';
str = s + 1;
}
}
if (s != str) {
*p = str;
p++;
}
int wordNum = p - pStr;
for (int i = 0; i < wordNum - 1; i++) {
for (int j = 0; j < wordNum - 1 - i; j++) {
if (*pStr[j] > *pStr[j + 1]) {
char* temp = pStr[j];
pStr[j] = pStr[j + 1];
pStr[j + 1] = temp;
}
}
}
return wordNum;
}
下标形式
for (int i = 0; i < wordNum - 1; i++) {
for (int j = 0; j < wordNum - 1 - i; j++) {
if (**(pStr + j) > **(pStr + j + 1)) {
char* temp = *(pStr + j);
*(pStr + j) = *(pStr + j + 1);
*(pStr + j + 1) = temp;
}
}
}
#include <stdio.h>
#include <string.h>
int GetWords(char *sentence, char *words[]);
void SortStrings( char *strs[],int count);
int main()
{
char str[200];
int nWords = 0;
char *words[20];
int i;
printf("input a string: ");
gets(str);
nWords = GetWords(str, words);
SortStrings(words,nWords);
puts("output:");
for(i=0; i<nWords; i++)
{
puts(words[i]);
}
return 0;
}
int GetWords(char *sentence,char *words[])
{
/******start******/
int i=0;
char *p;
p=strtok(sentence," ,.");
while(p!=NULL)
{
words[i]=p;
i++;
p=strtok(NULL," ,.");
}
return i;
/******end******/
}
void SortStrings(char *strs[],int count)
{
/******start******/
char *p;
int i,j,k;
for(i=0;i<count;i++){
for(j=i+1;j<count;j++)
{
if(strcmp(strs[i],strs[j])>0)
{
p=strs[i];
strs[i]=strs[j];
strs[j]=p;
}
}
}
/******end******/
}
void Input ( char *str ) {
char x;
x = getchar();
int i = 1;
while(x != '\n' && i < 81) {
if ((x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') || x == ' ') {
str[i-1] = x;
i++;
}
x = getchar();
}
*(str+i) = '\0';
}
int Split_Count ( char *str,char **pStr ) {
int count = 0;
while(*str) {
if (*str != ' ') {
*(pStr+count) = str;
count++;
}
while(*str) {
if (*str == ' ') {
*str = '\0';
break;
}
str++;
}
str++;
}
return count;
}