尋找一個字符串中的最長的單詞

#include <stdio.h>
#include <string.h>
int main(){
    int find_longest_word(char str[]);
    char str[100];
    printf("Please input a sentence, we will find the longest word of the sentence.\n");
    gets(str);
    int begin=find_longest_word(str);
    printf("The longest word of the sentence is :");
    while((str[begin]>'a'&&str[begin]<'z')||(str[begin]>'A'&&str[begin]<'Z')){
        printf("%c",str[begin]);
        begin++;
    }
}

int find_longest_word(char str[]){
    int current_length=0;//define the length of current word(定義當前的單詞的長度)
    int length=0;//define the length of the current longest word(定義當前遇到的最長的單詞的長度)
    int flag=1;//define the new word is begin(定義出現新的單詞的標誌)
    int current_place;//define the first position of current longest word(定義當前的單詞的第一個字母的位置)
    int place;//define the first position of the longest word(定義當前的字符串的最長的單詞的第一個字母的位置)
    for(int i=0;i<=strlen(str);i++){
        if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')){
            if(flag){//if the new word appear(當新的單詞出現的時候)
                current_place=i;//record the current word position(記錄下新的單詞的位置)
                flag=0;//next is not a new word, so we should reverse flag.(接下來的就不是新的單詞了,因此對flag取反)
            }else{
                current_length++;//increase the length of the word.(累加當前的單詞的長度)
            }
        }else{
            flag=1;//the new word will appear, so we should reverse the flag.(接下來可能會出現新的單詞,因此對flag取反)
            if(current_length>length){
            //if the length of the new word is longer than the previous word.(如果新的單詞的長度比之前的單詞的長度要長)
                length=current_length;//refresh the new length(更新最長的單詞的長度)
                place=current_place;//refresh the position of the new word(更新最長的單詞的位置信息)
                current_length=0;//empty the length of the word, because the new word is start.(新的單詞開始了,清空單詞長度)
            }
        }
    }
    return place;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章