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;
}
相关推荐
星期天21 小时前
3.2联合体和枚举enum,还有动态内存malloc,free,calloc,realloc
c语言·开发语言·算法·联合体·动态内存·初学者入门·枚举enum
自信150413057592 小时前
初学者小白复盘23之——联合与枚举
c语言·1024程序员节
秃秃秃秃哇3 小时前
C语言实现循环链表demo
linux·c语言·链表
小曹要微笑7 小时前
STM32H7系列全面解析:嵌入式性能的巅峰之作
c语言·stm32·单片机·嵌入式硬件·算法
松涛和鸣9 小时前
14、C 语言进阶:函数指针、typedef、二级指针、const 指针
c语言·开发语言·算法·排序算法·学习方法
星期天211 小时前
3.0 C语⾔内存函数:memcpy memmove memset memcmp 数据在内存中的存储:整数在内存中的存储 ⼤⼩端字节序和字节序判断
c语言·数据结构·进阶·内存函数·数据内存存储
代码雕刻家17 小时前
C语言的左对齐符号-
c语言·开发语言
star learning white19 小时前
xmC语言8
c语言·开发语言·算法
赖small强20 小时前
【Linux C/C++开发】第16章:多线程编程基础
linux·c语言·c++·多线程编程·进程和线程的本质区别
nono牛20 小时前
Android Binder C/C++ 层详解与实践
android·c语言·binder