笔试2--输出字符串中最长的单词

题目描述:对于一个字符串,输出该字符串中最长的单词。

代码:

#include<iostream>
#include<string>
using namespace std;

string MaxWord(const string str)
{
	string maxstr=new char[str.length()];//存最长单词
	string curstr=new char[str.length()];//记录当前单词

	int max=0;
	int cur=0;
	maxstr[0]='\0';

	for(int i=0;str[i]!='\0';++i)
	{
		if(isalpha(str[i]))
			curstr[cur++]=str[i];
		
		else if(cur!=0)
		{
			if(cur>max)
			{
				curstr[cur]='\0';
				maxstr=curstr;
				max=cur;
			}
			cur=0;
		}
	}
	
	if(cur>max)
	{
		curstr[cur]='\0';
		maxstr=curstr;
	}

	return maxstr;
}

int main()
{
	cout<<MaxWord("I am a student").c_str()<<endl;;
	cout<<MaxWord("hello world").c_str()<<endl;
	cout<<MaxWord("different").c_str()<<endl;
	cout<<MaxWord(" ").c_str()<<endl;
	cout<<MaxWord("Don not lose hope").c_str()<<endl;
	cout<<MaxWord("NULL").c_str()<<endl;
	cout<<MaxWord("123 25 ask").c_str()<<endl;
	cout<<MaxWord("563").c_str()<<endl;
	cout<<MaxWord("gh* ** huji").c_str()<<endl;
	cout<<MaxWord("**j %%kj").c_str()<<endl;
	cout<<MaxWord("good night").c_str()<<endl;

	return 0;
}

结果:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值