編程在一個已知的字符串中查找最長單詞,假定字符串中只含字母和空格,用空格來分隔單詞(只使用循環,數組)

   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);
    
    
    
    
    


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