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

来源:互联网 发布:离散化算法 编辑:程序博客网 时间:2024/04/26 08:49
   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);                    


0 1
原创粉丝点击