java 中replace方法?
Stting和StringBuffer有区别,但是两者的replace方法没什么区别,用法相同。
Stting和StringBuffer区别
String是固定不变的字符串,StringBuffer是可变字符串
每次对String类型字符串操作(赋值)都需要创建新对象(开辟堆空间),这样性能消耗大(当然数据量小当我没说)
而StringBuffer为了解决String的问题应运而生,明显的就是新增了两个方法(append、insert),用于解决字符串频繁的拼接,产生大量不必要的中间对象
简单说:每使用String赋值运算就需要创建一个String对象;而使用StringBuffer只需要创建一个对象,就可以将字符串的每次操作都在同一个对象上进行
案例(修改字符串“ABC”,并且拼接为aaddcc)
String a = “ABC”;
====>a = “ab"+"dd"+"ccc";
“ab”+“dd”产生一个中间对象“abdd”
“abdd”+“cc”产生一个对象“abddcc”
然后a变量也是新产生的,旧的已经释放掉了。
StringBuffer sb = new StringBuffer("ABC");
====>sb.replace(0,sb.length(),"ab").append("dd").append("cc");
始终在对象new StringBuffer("ABC")上修改、追加(拼接)字符串。
了解String、StringBuffer、StringBuilder的区别,需要了解它们的运行机制,自行了解,以上没有说全。
如果满意,望采纳,谢谢!
通常情况下,用string就行。
多线程大量数据下用后者
public class B {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 10; i++) {
sb.append(i);
}
sb.replace(1, 3, "abc");
/*
* StringBuffer中replace方法的注释 Replaces the characters in a substring of this
* sequence with characters in the specified String. The substring begins at the
* specified start and extends to the character at index end - 1 or to the end
* of the sequence if no such character exists. First the characters in the
* substring are removed and then the specified String is inserted at start.
* (This sequence will be lengthened to accommodate the specified String if
* necessary.) 自己去翻译,大致意思是将指定范围内的内容替换成指定的内容
*/
System.out.println(sb);
String s = new String("" + sb);
System.out.println(s.replace("a", "F"));
/*
* 这是String的replace方法 Returns a string resulting from replacing all occurrences
* of oldChar in this string with newChar. If the character oldChar does not
* occur in the character sequence represented by this String object, then a
* reference to this String object is returned. Otherwise, a String object is
* returned that represents a character sequence identical to the character
* sequence represented by this String object, except that every occurrence of
* oldChar is replaced by an occurrence of newChar. 自己去翻译,大致意思是将字符串中所有该内容替换成新的内容
*/
}
}