(C语言)写一个函数,将一个字符串中最长的单词输出

写一个函数,将一个字符串中最长的单词输出

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* output_long(char str[]) {
	static char s[1024];
	int right;//记录当前遍历的单词末尾字母的下标
	int count1 = 0;//记录当前遍历到的单词长度
	int count2 = 0;//记录遍历过的所有单词中最长的长度
	for (int i = 0; i < (int)strlen(str); ++i) {
		if (str[i] >= 'a'&&str[i] <= 'z' || str[i] >= 'A'&&str[i] <= 'Z')  {
			++count1;
			continue;
		}
		if (count1 > count2) {
			count2 = count1;
			right = i;
		}
		count1 = 0;//未跳出循环则说明上一个单词遍历结束,count1置0,便于记录下一个单词的长度
	}
	for (int i = 0; i < count2; ++i) {
		s[i] = str[i + right - count2];
	}
	return s;
}
void main() {
	char str[1024] = "I enjoy reading ,different kinds of books, but 'Harry Porter' is my favorite one.";
	printf("字符串为:%s\n", str);
	printf("字符串中最长的单词为:%s\n", output_long(str));
	system("pause");
}

在这里插入图片描述

  • 9
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值