StringBuilder类的replace()方法 (StringBuilder Class replace() method)
replace() method is available in java.lang package.
replace()方法在java.lang包中可用。
replace() method is used to replaces the set of character lies b/w beg and end parameter with the characters in the given string.
replace()方法用于用给定字符串中的字符替换b / w beg和end参数字符集。
replace() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
replace()方法是一种非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
replace() method may throw an exception at the time of replacing a set of characters with the given string.
用给定的字符串替换一组字符时, replace()方法可能会引发异常。
StringIndexOutOfBoundsException – This exception may throw when the first parameter beg < 0 , greater than length() or beg > end.
StringIndexOutOfBoundsException-当第一个参数beg <0 ,大于length()或beg> end时,可能引发此异常。
Syntax:
句法:
public StringBuilder replace(int beg, int end, String s);
Parameter(s):
参数:
int beg – represents the starting index to replace the set of character.
int beg –表示替换字符集的起始索引。
int end – represents the ending index till replace the set of characters.
int end –表示直到替换字符集为止的结束索引。
String s – represents the string that will replace contents b/w beg and end.
字符串s –表示将替换内容b / w开头和结尾的字符串。
Return value:
返回值:
The return type of this method is StringBuilder, it returns this StringBuilder object.
该方法的返回类型为StringBuilder ,它返回此StringBuilder对象。
Example:
例:
// Java program to demonstrate the example
// of replace (int beg , int end , String s)
// method of StringBuilder
public class Replace {
public static void main(String[] args) {
int beg = 5;
int end = 10;
String s = "Program";
// Creating an StringBuilder object
StringBuilder st_b = new StringBuilder("Java World ");
// Display st_b
System.out.println("st_b = " + st_b);
// By using replace(beg,end,s) method is to replace the string
// from index "beg" to index "end" in st_b with the given string
// ("Program")
st_b.replace(beg, end, s);
// Display st_b
System.out.println("st_b.replace(beg,end,s) = " + st_b);
}
}
Output
输出量
st_b = Java World
st_b.replace(beg,end,s) = Java Program
翻译自: https://www.includehelp.com/java/stringbuilder-replace-method-with-example.aspx