C语言写一个函数,输入一行字符,将此字符串中最短的单词输出
时间: 2024-02-15 22:04:43 浏览: 25
下面是一个 C 语言函数,可以实现输入一行字符,输出该字符串中最短的单词:
```c
#include <stdio.h>
#include <string.h>
void shortest_word(char *str) {
int i, j;
int len = strlen(str);
int min_len = len;
int start_index = 0;
int end_index = len - 1;
int word_start = 0;
int word_end = 0;
int word_len = 0;
int shortest_start = 0;
int shortest_end = 0;
int shortest_len = len;
// 去掉开头的空白字符
while (start_index < len && str[start_index] == ' ') {
start_index++;
}
// 去掉结尾的空白字符
while (end_index >= start_index && str[end_index] == ' ') {
end_index--;
}
for (i = start_index; i <= end_index;) {
// 找到单词的起始位置
while (i <= end_index && str[i] == ' ') {
i++;
}
if (i > end_index) {
break;
}
word_start = i;
// 找到单词的结束位置
j = i;
while (j <= end_index && str[j] != ' ') {
j++;
}
word_end = j - 1;
// 计算单词的长度
word_len = word_end - word_start + 1;
// 更新最短单词的信息
if (word_len < shortest_len) {
shortest_start = word_start;
shortest_end = word_end;
shortest_len = word_len;
}
i = j;
}
// 输出最短的单词
for (i = shortest_start; i <= shortest_end; i++) {
printf("%c", str[i]);
}
printf("\n");
}
```
该函数的参数为一个指向输入字符串的指针。在函数内部,首先去掉字符串开头和结尾的空白字符,然后逐个扫描字符串中的单词,找到最短的单词并输出。