华为机试题刷题笔记

1.一段英文字符串中最后一个单词的长度:
注意要点:cin和getline的区别;
cin为字符串输入时,遇见空格,编译器认为字符串输入结束;
getline可以输入含有空格的字符串;
安全起见,在C++中字符串的输入,最好都用getline;
cin作为输入字符串的例子如下图所示:结果输出的字符串为输入第一个空格之前的数据;
在这里插入图片描述
运行结果:
在这里插入图片描述
本机试题代码:

#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
int main(){
 int i;
 int count=0;
 string str;
 getline(cin,str);
 i=str.size()-1;
 while(str[i]!=' '&&i>=0){
  count++;
  i--;
 }
 cout<<"本句子最后一个单词的长度为:"<<count<<endl;
 system("pause");
 return 0;
}

运行结果:
在这里插入图片描述
2.输入一个字符串和一个字符,统计该字符在该字符串中出现的次数:
注意点:只要是一个字母就行,不区分大小写;
需要用到tolower函数;
代码:

#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
int main(){
 string str;
 int count,i;
 char ch;
 count=0;
 getline(cin,str);
 cin>>ch;
 for(i=str.size()-1;i>=0;i--){
  if(tolower(str[i])==tolower(ch)){
   count++;
  }
 }
 cout<<count<<endl;
 system("pause");
 return 0;
}

在这里插入图片描述
3.输入一串整数,整数去重,输出排好序的结果:
学习要点:sort和unique函数的用法;
版本一:
不用任何库函数;
冒泡排序加排序后比较重复数字进行剔除

#include<iostream>
#include<stdlib.h>
using namespace std;
int main(){
	int n;//数组长度
	int *arr;
	cout<<"请输入该数组的长度:"<<endl;
	for(int i=0;i<n;i++){
		cin>>arr[i];
	}
	//冒泡排序
	for(i=1;i<n;i++){
		for(j=0;j<n-i;j++){
			if(arr[j]>arr[j+1]){
				int temp=arr[j];
				arr[j]=arr[j+1];
				arr[j+1]=temp;
			}
		}
	}
	//去重
	for(int i=0;i<n;i++){
		if(arr[i]!=arr[i+1]){
		cout<<arr[i]<<' ';
		}
	}
	system("pause")
	return 0;
}

运行结果
在这里插入图片描述
版本二:
利用容器里面的set的特点,不重复且排好序;
代码:

#include<stdlib.h>
#include<iostream>
#include<set>
using namespace std;
int main(){
	int n;//数组大小
	cout<<"请输入数组长度:"<<endl;
	while(cin>>n){
		set<int> arr;
		for(int j=0;j<n;j++){
			int temp;
			cout<<temp;
			arr.insert(temp);
		}
		for(set<int>::iterator iter=arr.begin();iter!=arr.end();iter++){
			cout<<*iter<<' ';
		}
		cout<<endl;
	}
  system("pause");
  return 0;
}

运行结果:
在这里插入图片描述
版本三:
主要是利用了sort函数和unique函数;
sort(itera,iterb),对迭代器表示的地址之间的数值进行从小到大的排序;默认从小到大;
unique函数的用法:
功能:对有序的容器重新排序,将第一次出现的元素从前往后排,其他重复出现的元素依次排在后面;
返回值:返回迭代器;指向重复元素的首地址
在这里插入图片描述
erase函数:
erase(itera,iterb)
擦除从迭代器a到迭代器b之间的元素;
代码:

#include<iostream>
#include<stdlib.h>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
	int n;
	cout<<"请输入数组长度:"<<endl;
	while(cin>>n){
		vector<int> arr;
		for(int i=0;i<n;i++){
			int temp;
			cin>>temp;
			arr.pushback(temp);
		}
		sort(arr.begin(),arr.ennd());
		vector<int>iterator::iter;
		iter=unique(arr.begin().arr.end());
		if(iter!=arr.end()){
			arr.erase(iter,arr.end())
		}
		for(iter=arr.begin();iter!=arr.end();iter++){
			cout<<*iter<<endl;
		}
	}
	system("pause");
	return 0;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值