创建用户库strpro.h,其中包含getString、sort和read函数。
在main函数中提示用户输入一句英文句子,要求:
调用getString函数将该英文句子读入二维字符数组,然后调用函数sort,利用选择或冒泡算法对上述句子中的单词进行排序(按字母序)。
#include <stdio.h>
#include "stropro.h"
int main()
{
char sentence[100][100];
int count=0;
printf("Enter a sentence: \n");
count=getString(sentence);
sort(sentence,count);
for(int i=0;i<count;i++)
{
puts(sentence[i]);
}
return 0;
}
说一下这些函数的作用
#include <stdio.h>
#include <string.h>
#include "strpro.h" // 头文件 strpro.h
int main(void)
{
char sentence[100][100]; // 定义二维字符数组 sentence
int num_words;
// 读入句子
num_words = getString(sentence);
// 对句子中的单词进行排序
sort(sentence, num_words);
// 输出排序后的句子
read(sentence, num_words);
return 0;
}
// strpro.h
#ifndef STRPRO_H
#define STRPRO_H
int getString(char sentence[][100]);
void sort(char sentence[][100], int num_words);
void read(char sentence[][100], int num_words);
#endif
// getString.c
#include <stdio.h>
#include <string.h>
int getString(char sentence[][100])
{
printf("Enter a sentence: ");
char c;
int i = 0, j = 0;
while ((c = getchar()) != '\n')
{
if (c == ' ')
{
i++;
j = 0;
}
else
{
sentence[i][j++] = c;
}
}
sentence[i][j] = '\0';
return i + 1;
}
// sort.c
#include <stdio.h>
#include <string.h>
void sort(char sentence[][100], int num_words)
{
// 选择排序法
for (int i = 0; i < num_words - 1; i++)
{
int min_idx = i;
for (int j = i + 1; j < num_words; j++)
{
if (strcmp(sentence[j], sentence[min_idx]) < 0)
{
min_idx = j;
}
}
if (min_idx != i)
{
char temp[100];
strcpy(temp, sentence[i]);
strcpy(sentence[i], sentence[min_idx]);
strcpy(sentence[min_idx], temp);
}
}
}
// read.c
#include <stdio.h>
void read(char sentence[][100], int num_words)
{
printf("Sorted sentence: ");
for (int i = 0; i < num_words; i++)
{
printf("%s ", sentence[i]);
}
printf("\n");
}
是不是自定义头文件实现功能?
你可以使用以下代码来创建用户库strpro.h,并在main函数中调用这些函数:
#include <stdio.h>
#include <string.h>
// getString函数,用于读入一句英文句子
void getString(char str[][50])
{
printf("请输入一句英文句子:\n");
gets(str);
}
// sort函数,用于对单词进行排序
void sort(char str[][50])
{
int i, j, k;
char temp[50];
// 冒泡排序法
for (i = 0; i < strlen(str); i++)
{
for (j = 0; j < strlen(str) - i - 1; j++)
{
if (strcmp(str[j], str[j + 1]) > 0)
{
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}
}
// read函数,用于输出排序后的单词
void read(char str[][50])
{
int i;
printf("排序后的单词为:\n");
for (i = 0; i < strlen(str); i++)
printf("%s ", str[i]);
printf("\n");
}
然后,在main函数中,你可以使用以下代码来调用这些函数:
#include <stdio.h>
#include <string.h>
#include "strpro.h"
int main()
{
char str[20][50]; // 存储输入的句子
getString(str);
sort(str);
read(str);
return 0;
}
注意:在这里,我们使用了冒泡排序法来对单词进行排序。如果你想使用选择排序法,可以修改sort函数中的代码。