UVA - 10115 - Automatic Editing

本文介绍了一个UVA在线评测平台上的字符串替换题目,使用C++中的string类及vector容器实现从左到右的字符串查找和替换,提供完整的代码示例。

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=96&page=show_problem&problem=1056


题意:

  进行字符串替换。输入几个规则。每个规则都是a string to find & a string to replace。最后是一行待处理字符串。

  每个规则找的时候,每次都是从左到右找~注意


解题:

  用string & string.find & string.replace解决。。。(PS:想起几年前去机试,那个时候不会string和str,做不出来,好丢人。。。)

  最近喜欢用vector & string来存东西,哈哈,不用理会大小~


#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
using namespace std;


int main()
{
	int nRule;

	while ( cin >>nRule )
	{
		if ( nRule == 0 )
		{
			break;
		} // end if

		// ignore the \n that just input
		cin.ignore();

		vector <string> vCode;
		vector <string> vCodeRe;
		string strIn;
		for ( int i=0; i<nRule; i++ )
		{
			// input string to find
			getline(cin, strIn);
			vCode.push_back(strIn);

			// input string to replace
			getline(cin, strIn);
			vCodeRe.push_back(strIn);
		} // end for

		// get target string
		string tarStr;
		getline(cin, tarStr);

// 		cout <<"Before: " <<tarStr <<"\n";

		// for each rule
		for ( int i=0; i<nRule; i++ )
		{
			// one rule round
			int nPos = 0;
			while ( 1 )
			{
				nPos = tarStr.find(vCode[i], 0);
				if ( nPos == string::npos )
				{
					break;
				} // end if
				else
				{
					tarStr.replace(nPos, vCode[i].length(), vCodeRe[i]);
				} // end else
			} // end while
		} // end for

// 		cout <<"After: " <<tarStr <<"\n";
// 		cout <<"\n";
		
		cout <<tarStr <<"\n";
		
	} // end while
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值