寻找一个字符串中的最长的单词

#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;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值