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;
}
相关推荐
集芯微电科技有限公司2 小时前
15V/2A同步开关型降压单节/双节锂电池充电管理IC支持输入适配器 DPM 功能
c语言·开发语言·stm32·单片机·嵌入式硬件·电脑
zz34572981134 小时前
c语言基础概念9
c语言·开发语言
v_for_van5 小时前
力扣刷题记录4(无算法背景,纯C语言)
c语言·算法·leetcode
启友玩AI5 小时前
方言守护者:基于启英泰伦CI-F162GS02J芯片的“能听懂乡音”的智能夜灯DIY全攻略
c语言·人工智能·嵌入式硬件·ai·语音识别·pcb工艺
EmbedLinX6 小时前
Linux 之设备驱动
linux·服务器·c语言
小柯博客6 小时前
从零开始打造 OpenSTLinux 6.6 Yocto 系统 - STM32MP2(基于STM32CubeMX)(六)
c语言·git·stm32·单片机·嵌入式硬件·开源·yocto
你怎么知道我是队长7 小时前
C语言---排序算法6---递归归并排序法
c语言·算法·排序算法
梵刹古音7 小时前
【C语言】 字符数组与多维数组
c语言·数据结构·算法
时时三省8 小时前
【时时三省】(C语言基础)共用体/联合体
c语言
牛马大师兄8 小时前
数据结构复习 | 单向链表
c语言·数据结构·笔记·链表