华为机试题(替换字符串)——Java解法

package com.abuge;

import java.io.IOException;
import java.io.InputStream;
/**
 * 题目要求:输入一个字符串,然后再输入一个整数,就是替换字符串的次数,然后依次输入要替换的字符串
 * @author AbuGe
 *例如:
 *输入:
 *abcdef
 *2
 *ab->xy
 *cd->pq
 *输出:
 *xypqef
 */
public class ReplaceString 
{
	public static void main(String[] args) throws IOException
	{
		//定义输入的字符串
		String strInput = null;
		
		//键盘录入数据
		InputStream in = System.in;
		
		//定义一个缓冲区
		StringBuilder sb = new StringBuilder();
		
		int count = 0;
		
		while(true)
		{
			int ch = 0;
			while(true)
			{
				ch = in.read();
				if(ch == '\r')
					continue;
				
				if(ch == '\n')
				{
					strInput = sb.toString();
					sb.delete(0, sb.length());
					break;
				}
				sb.append((char)ch);
			}
			//处理连续回车的情况
			if(strInput.length() == 0)
			{
//				System.out.println("输入字符串只有回车符。。。。。");
				continue;
			}
				
			
			//定义存储替换字符串的次数
			int num = in.read() - '0';
			count = 0;
			String oldStr = null;
			String newStr = null;
			//继续录入,并对字符串进行处理
			while(count< num)
			{
				//录入原有需替换的字符
				while(true)
				{
					ch = in.read();
					if(ch== '\r' || ch == '\n')
						continue;
					
					if(ch == '-')
						continue;
					
					if(ch == '>')
					{
						oldStr = sb.toString();
						sb.delete(0, sb.length());
						break;
					}
					sb.append((char)ch);
				}
				
				//录入替换后的字符串
				while(true)
				{
					ch = in.read();
					if(ch == '\r')
						continue;
					
					if(ch == '\n')
					{
						newStr = sb.toString();
						sb.delete(0, sb.length());
						break;
					}
					sb.append((char)ch);
				}
				
				if(strInput.contains(oldStr))
				{
					strInput = strInput.replace(oldStr, newStr);
				}
				count++;
			}
			System.out.println(strInput);
		}
	}	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值