java三个字符_java字符替换三个简单实例

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();

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值