java字符替换,在java中进行字符替换我们也可以用到replace函数,下面来看看三个实例的方法.
public class MainClass
{
public static void main( String args[] )
{
String s1 = new String( "hello" );
String s2 = new String( "GOODBYE" );
String s3 = new String( " spaces " );System.out.printf( "s1 = %sns2 = %sns3 = %snn", s1, s2, s3 );
// test method replace
System.out.printf("Replace 'l' with 'L' in s1: %snn", s1.replace( 'l', 'L' ) );} // end main
}
输出结果
s1 = hello
s2 = GOODBYE
s3 = spaces
Replace 'l' with 'L' in s1: heLLo
实例二
public class Main {
public static void main(String[] argv) throws Exception {
System.out.println(replace("this is a test", "is", "are"));
}static String replace(String str, String pattern, String replace) {
int start = 0;
int index = 0;
StringBuffer result = new StringBuffer();while ((index = str.indexOf(pattern, start)) >= 0) {
result.append(str.substring(start, index));
result.append(replace);
start = index + pattern.length();
}
result.append(str.substring(start));
return result.toString();
}
}
看一个面试代码 java中用指定的字符串替换指定的字符串
public class StringReplacer
{
private String str;public StringReplacer(String src, String before, String after) {
str = replaceString(src, before, after);
}public String toString() {
return str;
}public static String replaceString(String src,String before,String after) {
StringBuffer sb = new StringBuffer();
int oldidx = 0;
int idx = src.indexOf(before);
while (idx != -1) {
sb.append(src.substring(oldidx, idx)).append(after);
oldidx = idx + before.length();
idx = src.indexOf(before, oldidx);
}
if (oldidx < src.length())
sb.append(src.substring(oldidx));
return sb.toString();
}
}