C语言--统计字符串中最长的单词

输入:一串单词,以空格作为单词的间隔。

输出:最长的单词

代码

思路: 如果不是分隔符且inWord=0,说明首次进入一个新单词,记录单词开始的下标

如果是分隔符且且inWord=1,说明退出单词,计算单词长度并与之前的最长单词对比,记录最新的最长的单词。

注意:最后一个单词如果一直到末尾,需要出循环后单独对比。

c 复制代码
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void longestWord(char *str) {
    int wordStartIndex = 0; //记录每个单词开始
    int wordLength = 0;  //记录每个单词长度
    int maxLen = 0;
    int maxStartIndex = 0;
    int inWord = 0;
    int i;
    for (i = 0; str[i] != '\0'; i++) {
        if (isspace(str[i])) {
            if (inWord) {
                // 退出一个单词
                wordLength = i - wordStartIndex; //目前这个单词长度
                inWord = 0;
                if (maxLen < wordLength) {
                    // 存在单词比之前的单词长
                    maxLen = wordLength;
                    maxStartIndex = wordStartIndex;
                }
            }
        } else {
            if (!inWord) {
                wordStartIndex = i; //进入一个新单词,记录这个单词起始位置
            }
            inWord = 1;
        }
    }
    if (inWord) {
        // 最后一个单词后面没空格
        wordLength = i - wordStartIndex;
        if (maxLen < wordLength) {
            maxStartIndex = wordStartIndex;
        }
    }
    for (int j = maxStartIndex; ; j++) {
        if (isspace(str[j]) || str[j] == '\0') {
            break;
        }
        printf("%c", str[j]);
    }
    printf("\n");
}

运行

c 复制代码
int main() {
    char str[]="aaaaaa bb  ccc";
    char str2[]="a bc ddddddddd";
    char str3[]="i am cccccc   ";
    longestWord(str);
    return 0;
}
相关推荐
Navigator_Z13 小时前
LeetCode //C - 1289. Minimum Falling Path Sum II
c语言·算法·leetcode
himobrinehacken13 小时前
取模运算的汇编奥秘揭秘
c语言·安全
青岚_Nox16 小时前
C语言实战:带你手写一个带"计时功能"的猜数字小游戏
c语言
iotxiaohu18 小时前
用 cflow 查看 C 函数调用关系
c语言·开发语言·cflow
iCxhust20 小时前
51单片机电力载波应用开发(九)51产品化
c语言·数据库·嵌入式硬件·mysql·51单片机·软件工程·c51
Logic10121 小时前
C语言/数据结构字符串题解:统计“chhc“子串权值总和——一次遍历模式匹配
c语言·数据结构·算法·字符串·时间复杂度·空间复杂度·ascii
m0_547486661 天前
《数据结构 (C语言)》期末试卷及答案(10套)2026版
c语言·开发语言·数据结构
八月的雨季 最後的冰吻1 天前
FFmepg-- 42-ffplay.c 线程安全机制深度分析
c语言·安全·ffmpeg
逐光者9331 天前
滤波器的 R 与 C 如何选择:从截止频率到工程实践
c语言·开发语言·r语言
水饺编程1 天前
第2章:Linux 基础,whoami 命令
linux·c语言·汇编