写函数,输入一行字符输出最长的单词。
#include <stdio.h>#include <string.h>
int alphabetic(char c)
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
return(1);
}
else
{
return(0);
}
}
int longest(char string[])
{
int len = 0;
int i;
int length = 0;
int flag = 1;
int place = 0;
int point;
for (i = 0; i <= strlen(string); i++)
{
if (alphabtic(string))
{
if (flag)
{
point = i;
flag = 0;
}
else
{
len++;
}
}
else
{
flag = 1;
if (len >= length)
{
length = len;
place = point;
len = 0;
}
}
}
return(place);
}
int main(void)
{
int i;
char line;
printf("输入一行:\n");
gets_s(line);
printf("最长的单词是:");
for (i = longest(line); alphabetic(line); i++)
{
printf("%c", line);
}
printf("\n");
return 0;
} 1.函数名字写不对,报错都提示了,函数名是 alphabetic 不是 alphabtic
2.get_s()函数我dev用不了,用了gets()代替了,如果代码有问题,换回get_s()试试
#include <stdio.h>
#include <string.h>
int alphabetic(char c)
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
return(1);
}
else
{
return(0);
}
}
int longest(char string[])
{
int len = 0;
int i;
int length = 0;
int flag = 1;
int place = 0;
int point;
for (i = 0; i <= strlen(string); i++)
{
if (alphabetic(string))
{
if (flag)
{
point = i;
flag = 0;
}
else
{
len++;
}
}
else
{
flag = 1;
if (len >= length)
{
length = len;
place = point;
len = 0;
}
}
}
return(place);
}
int main(void)
{
int i;
char line;
printf("输入一行:\n");
gets(line);
printf("最长的单词是:");
for (i = longest(line); alphabetic(line); i++)
{
printf("%c", line);
}
printf("\n");
return 0;
} 本帖最后由 jackz007 于 2021-9-27 17:25 编辑
#include <stdio.h>
void longest(char line[])
{
int i , j , m ;
char word ;
// 获取最长单词长度
for(i = j = m = 0 ; line ; i ++) {
if(line >= 'A' && line <= 'Z' || line >= 'a' && line <= 'z') {
j ++ ;
} else {
if(j && j > m) m = j ;
j = 0 ;
}
}
if(j && j > m) m = j ;
printf("最长单词为 %d 个字符\n" , m) ;
// 提取所有最长单词
for(i = j = 0 ; line ; i ++) {
if(line >= 'A' && line <= 'Z' || line >= 'a' && line <= 'z') {
word = line ;
word = '\0' ;
} else {
if(j == m) printf("%s\n" , word) ;
j = 0 ;
}
}
if(j == m) printf("%s\n" , word) ;
}
int main(void)
{
char s ;
// 取得键盘输入
gets(s) ;
longest(s) ;
}
编译、运行实况:
D:\0002.Exercise\C>g++ -o x x.c
D:\0002.Exercise\C>x
Abc12,CDEF,12HIJKm,88KLJMi,5588ABCDE
最长单词为 5 个字符
HIJKm
KLJMi
ABCDE
D:\0002.Exercise\C>
页:
[1]