CS106B Section Solutions #1

Problem 1: Removing all occurrences of a character

代码:

#include <iostream>
using namespace std;

string CensorString1(string text, string remove);
void CensorString2(string &text, string remove);


int main()
{
	string text="hauzcxbdsbhrjdhyhghzyyx";
	string remove="zxy";
	cout <<CensorString1(text,remove)<< endl;
	CensorString2(text,remove);
	cout <<text<< endl;
}


string CensorString1(string text, string remove)
{
	string result="";
	for(int i=0; i<text.length(); i++)
	{
		 bool remain=true;
		 for(int j=0; j<remove.length(); j++)
		 {
		 	if(text[i]==remove[j])
		 	{
			  remain=false;
		 	  break;
		    }
		 }
		 if(remain)
		 {
		 	result+=text[i];
		 }
	} 
	return result;
} 

void CensorString2(string &text, string remove)
{

		 for(int j=0; j<remove.length(); j++)
		 {
		 	int pos=0;
		 	while( (pos=text.find(remove[j])) != string::npos)
		 	{
		    	text.erase(pos,1);
		    }
		 }

} 

结果:

Problem 2: Files and Structs

代码:

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

struct statsT {
int low;
int high;
double average;
};
statsT CalculateStatistics(string filename);

int main()
{
	statsT chengji;
	string filename="zxy.txt" ;
	chengji=CalculateStatistics(filename);
	cout<<"average is "<<chengji.average <<endl;
}


statsT CalculateStatistics(string filename) {
	statsT stats;	
	stats.low = 101;
	stats.high = -1;
	int total = 0;
	int count = 0;

	ifstream in;
	in.open(filename.c_str());
	
	//if (in.fail()) Error("Couldn't read '" + filename + "'");
	
	while(true) 
	{
		int num;
		in >> num;
		// Check that we read successfully
		if (in.fail()) break;
		// Update or data if we need to
		if (num < stats.low) stats.low = num;
		if (num > stats.high) stats.high = num;
		cout<<num<<endl;
		total += num;
		count++;
	}

	stats.average = double(total)/count;

	in.close();
	return stats;
}

结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值