【C++】实验五 指针


字符串统计

【问题描述】

在进行文章重复度检查时,经常需要统计一段英文中的单词数量,并找出长度最长的单词。

设有如下定义:char str[500];

编写程序,通过利用cin.getline(str,500);实现从键盘输入一小段英文(其中可以包含空格,但在同一行),利用函数统计该段英文中包含几个单词,输出统计出的单词数量、最长单词的长度以及长度最长的单词,空格隔开。

注意:函数声明使用void split(char *str);如果有最长的单词不只一个,输出最先找到的那个。

【输入形式】一小段英文,不要超过500个字符

【输出形式】单词数量、最长单词的长度以及长度最长的单词,空格隔开。

【样例输入】welcome to china university of mining and technology

【样例输出】8 10 university

#include<iostream>
using namespace std;
void split(char *str)
{
	int num_word=0;
	int temp=0,maxlen=0,maxwhere=0;
	for(int i=0;str[i]!='\0';i++)
	{
		if(str[i+1]=='\0'&&str[i]>='a'&&str[i]<='z') str[i+1]=' ';
		if(str[i]==' ')
		{
			num_word++;
			if(temp>maxlen)
			{
				maxlen=temp;
				maxwhere=i-temp;
				temp=0;
			}
			else temp=0;
		}
		else
		{
			temp++;
		}
	}
	cout << num_word << " " << maxlen << " ";
	while(str[maxwhere]!=' ') cout << str[maxwhere++];

}
int main()
{
	char str[500];
	cin.getline(str,500);
	split(str);
	return 0;
}


复数提取

【问题描述】

编写如下原型的函数:

void split(double x,intiPart,doublefPart);

提取出数据x的整数部分与小数部分,分别放于iPart与fPart处,由于形参iPart与fPart都是指针,从而可实现将这两个结果“带回”到主函数中。

在主函数中

输入一个数

输出它的整数部分和小数部分,用空格隔开。

提示:一个double类型数,强制类型转换后就是int,也就是整数部分,差为小数部分。这两个值用指针iPart和指针fPart带回(通过修改指针的目标变量值。)

【输入形式】一个数

【输出形式】整数部分 小数部分,用空格隔开

【样例输入】12.3
【样例输出】12 0.3

#include<iostream>
using namespace std;
void split(double x,int *iPart,double *fPart)
{
	*fPart = x-(int)x;
	*iPart=(int)x;
}
int main()
{
	int zhengshu;
	double xiaoshu,x;
	cin >> x;
	split(x,&zhengshu,&xiaoshu);
	cout << zhengshu << " " << xiaoshu;
	return 0;
}

找子串最后一次出现的头字符位置

【问题描述】

编制具有如下原型的函数findLast:

charfindLast(charsourceStr,char*subStr);

findLast函数则要返回源串sourceStr中最后一次出现subStr子字符串的头字符位置。

而后编制主函数,输入两个字符串,将它们用作实参来调用这两个函数,如果返回NULL输出-1,否则输出子字符串出现时头字符在原字符串的下标,每个结果占一行。

要求实现程序中不可使用“string.h”头文件内有关寻找子串的标准库函数。

【输入形式】输入源串sourceStr,子字符串subStr。

【输出形式】子字符串subStr最后一次在源串sourceStr中出现的位置

【样例输入】

welcometochinauniversityofminingandtechnology

in

【样例输出】29

#include<iostream>
using namespace std;
char*findLast(char*sourcestr,char*substr)
{
	char *ans=NULL;
	char *temp1,*temp2;
	for(int i=0;sourcestr[i]!='\0';i++)
	{
		if(sourcestr[i]==*substr)
		{
			int flag=1;
			temp1=sourcestr+i;
			temp2=substr;
			while(*temp2!='\0')
			{
				if(*temp1!=*temp2) flag=0;
				temp1++;temp2++;
			}
			if(flag) ans=sourcestr+i;
		}
	}
	return ans;
}
int main()
{
	char sourcestr[500],substr[500];
	char *ans;
	cin >> sourcestr >> substr;
	ans=findLast(sourcestr,substr);
	if(ans) cout << ans-sourcestr;
	else cout << -1;
	return 0;
}

  • 17
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值