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);
}
}
}
华为机试题(替换字符串)——Java解法
最新推荐文章于 2023-08-26 13:07:25 发布