写一个函数,输入一行字符,将此字符串中最长单词输出(C语言)
题目要求:如标题
思路:
- 有一个原来字符串str,定义一个max字符串和temp字符串
- 先令max[0]=’\0’
- 对于i=0,在s1[i]!=’\0’的情况下令i递加
- 此时,令j=0,当str[i]是字母的时候,temp[j++]=str[i++]
- 令最后的temp[j]=’\0’
- 如果max的长度<temp的长度,则将temp复制给max
- 最后输出max
以下是具体代码:
#include <stdio.h>
#include <string.h>
int main()
{
void longest_vocabulary(char str[]);
char string[1000];
printf("please enter a string: ");
gets(string);
longest_vocabulary(string);
return 0;
}
void longest_vocabulary(char str[])
{
char max[30],temp[30];
max[0]='\0';
int i,j;
for(i=0;str[i]!='\0';i++)
{
j=0;
while((str[i]>='A' && str[i]<='Z') || (str[i]>='a' && str[i]<='z'))
temp[j++]=str[i++];
temp[j]='\0';
if(strlen(max)<strlen(temp))
strcpy(max,temp);
}
printf("The longest word: ");
puts(max);
}
本文介绍如何用C语言编写一个函数,该函数接收一行字符并找出其中最长的单词。通过定义字符串变量,遍历输入字符,判断字母并更新最长单词,最终输出结果。
691





