编程在一个已知的字符串中查找最长单词,假定字符串中只含字母和空格,用空格来分隔单词(只使用循环,数组)

   char str[] = "Image hk a lanoucompany think i can do zhe work very good  Thank you ";
    int maxLength = 0;//存储最长单词的长度
    int length  = 0;//用来记录单词的长度
    int maxIndex = 0;//记录最长单词的开始下标
    //因为不知道字符的个数,使用while循环
    int i = 0;
    while (str[i] != '\0') {
        if (str[i] != ' ') {
            length ++;
            
        }else{
            //当遇到空格时
            if (length > maxLength) {
                maxLength = length;
                maxIndex = i - length;
            }
            length = 0;
        }
        
        i++;
    }
 
//如果最后一个单词后面没有空格直接到\0.并且最后一个单词的长度也是最长的此时就会缺少一个和maxLength比的过程.所以我们只需要在while循环的外部加上比较操作即可.
    if (length > maxLength) {
        maxLength = length;
        maxIndex = i - maxLength;
    }
    //输出最长单词
    for (int i = maxIndex; i < maxIndex + maxLength; i++) {
        printf("%c",str[i]);
    }
    
    printf("\nmaxLength = %d\nmaxIndex = %d",maxLength,maxIndex);
    
    
    
    
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值