- 论坛徽章:
- 0
|
两者都是处理字符串的类,但是它们有一个最大的区别,那就是:String对象是存储你不能改动的文本字符串,相反,如果你希望改动,则应使用StringBuffer类作为替换。
eg1:
......
//omit some code
String s1="You are hired!";
System.out.println(s1.replace('h','f'));//用f把字串中的h替换了
System.out.println(s1);
......
//omit some code
运行结果:
You are fired!
You are hired!
结果分析:
由结果可知,s1的值并没有被改变,而第一行结果只是屏幕内容的替换。
eg2:
......
//omit some code
StringBuffer s2=new StringBuffer("Hello from Java!");
s2.replace(6,10,"to");
System.out.println(s2);
......
//omit some code
运行结果:
Hello to Java!
结果分析:
显然,s2的值已改变.
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/18918/showart_304197.html |
|