一道简单的面试题,这里用了两种方法,都是基本用法,主要是分析不同方法之间带来的区别,在使用中可以避免小麻烦提高书写效率。
package test;
public class replacechar {
//要解析的字符串 r后面是两个空格
String exp1 = "d a ad ad fs ds fdsf gdf gf gfd r dsd";
public void repalce1(){
if(exp1==null)
return;
StringBuffer outputBuffer=new StringBuffer();
for(int i=0; i<exp1.length(); i++) {
//这里可以直接使用' '进行判断,因为是逐字符判断(charat方法)
if(exp1.charAt(i)==' ') {
outputBuffer.append("@");
} else {
//直接放在StringBuffer类的实例中输出
outputBuffer.append(String.valueOf(exp1.charAt(i)));
}
}
System.out.println(outputBuffer);
}
public void repalce2(){
//这里split方法有很多用法,这里分隔了中间的多个空白符
String[] strings = exp1.split("\\s+");
String result = new String();
for (int i = 0; i < strings.length; i++) {
//强迫症犯了加上去的。。。。。。
if (i == strings.length - 1) {
result += strings[i];
break;
}
result +=strings[i]+"@";
}
System.out.println(result);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
replacechar a1 = new replacechar();
a1.repalce1();
a1.repalce2();
}
}
结果为:
d@a@ad@ad@fs@ds@fdsf@gdf@gf@gfd@r@@dsd
d@a@ad@ad@fs@ds@fdsf@gdf@gf@gfd@r@dsd