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;
}
相关推荐
hazy1k7 分钟前
ESP32基础-Socket通信 (TCP/UDP)
c语言·单片机·嵌入式硬件·网络协议·tcp/ip·udp·esp32
dvvvvvw10 分钟前
x的y次幂的递归函数.c
c语言
Want5953 小时前
C/C++跳动的爱心②
c语言·开发语言·c++
大牙Adela3 小时前
在Mac上通过Multipass虚拟机中的Ubuntu系统使用Graphviz工具
c语言·qt·ubuntu·macos·multipass·graphviz
无限进步_3 小时前
C语言动态内存管理:掌握malloc、calloc、realloc和free的实战应用
c语言·开发语言·c++·git·算法·github·visual studio
EXtreme354 小时前
【C 语言硬核避坑】动态内存管理:从野指针到柔性数组的“防爆”指南
c语言·动态内存管理·内存泄漏
embrace996 小时前
【C语言学习】数据在内存中存储
java·c语言·开发语言·汇编·c++·学习·算法
小龙报6 小时前
《算法通关指南:数据结构和算法篇 --- 链表相关算法题》--- 1. 队列安排,2.约瑟夫问题
c语言·数据结构·c++·算法·创业创新·学习方法·visual studio
合作小小程序员小小店7 小时前
console开发,命令行界面%超市管理系统%开发,基于vs2019,c,struct,txt数据存储
c语言·开发语言
序属秋秋秋7 小时前
《Linux系统编程之进程基础》【进程切换 + 进程调度】
linux·运维·服务器·c语言·c++·ubuntu·系统编程