1. 程式人生 > 其它 >C語言-輸出一個句子中最長的單詞

C語言-輸出一個句子中最長的單詞

#include <stdio.h> #include <string.h> #include <ctype.h>
int main() { int longest_i(char * p);
char str[1000]; gets(str);//輸入
int max_i,i; max_i = longest_i(str);//獲取最長單詞的首字母下標 //輸出這個最長的單詞 for (i = max_i; isalpha(str[i]); i++) printf("%c", str[i]); puts("");//輸出一個換行
return 0; }
//找到字串中最長單詞的起始下標 int longest_i(char * p){
int maxs_index=0,i,count=0,maxl=0,dqs_index=0; int flag=0;//1在一個單詞內 0未在單詞內 for (i = 0; i <= strlen(p); i++){ if(isalpha(*(p+i))){ //當前字元是字母 if(!flag){ //如果是單詞的第一個字母 flag=1; //標記進入一個單詞 dqs_index = i; //這個單詞的起始下標是i } count++; }else{ //當前字元不是字母 //如果最大長度有值且當前單詞的長度大於之前的最大長度,或者最大長度還沒有值(當前是第一個單詞) if((maxl && count>maxl) || !maxl){ maxl = count; maxs_index = dqs_index; } flag = 0;//標記為非單詞狀態 count=0;//單詞長度計數變數賦0 } } return maxs_index; }