Java StringBuffer delete()方法及示例
java.lang.StringBuffer.delete()是Java中的一个内置方法,用于删除或删除该序列的子串中的字符。该子串从指定的索引起点开始,延伸到索引终点的字符。
语法:
public StringBuffer delete(int start_point, int end_point)
参数:该方法接受两个整数类型的参数:
start_point – 这是指起始索引,包含在计数中。
end_point – 这是指结束索引,不包含在计数中。
返回值:该方法在删除参数中提到的范围所形成的子串后返回字符串。
异常情况。如果start_point是负数,大于length(),或者大于end_point,会发生StringIndexOutOfBoundsException。
例子 :
输入: String = “Apple”
start_point = 2
end_point = 4
输出:Ape
输入: String = “GeeksforGeeks”
start_point = 2
end_point = 7
输出:GerGeeks
下面的程序说明了java.lang.StringBuffer.delete()方法:
程序1:
// Java program to illustrate the
// java.lang.StringBuffer.delete()
import java.lang.*;
public class geeks {
public static void main(String[] args)
{
StringBuffer sbf = new StringBuffer("Geeksforgeeks");
System.out.println("string buffer = " + sbf);
// Deleting characters from index 2 to 7
sbf.delete(6, 8);
System.out.println("After deletion string buffer is = " + sbf);
}
}
输出:
string buffer = Geeksforgeeks
After deletion string buffer is = Geeksfgeeks
程序2:
// Java program to illustrate the
// java.lang.StringBuffer.delete()
import java.lang.*;
public class geeks {
public static void main(String[] args)
{
StringBuffer sbf = new StringBuffer("Welcome to Geeksforgeeks");
System.out.println("string buffer = " + sbf);
// deleting characters from index 5 to index 9
sbf.delete(5, 9);
System.out.println("After deletion string buffer is = " + sbf);
}
}
输出:
string buffer = Welcome to Geeksforgeeks
After deletion string buffer is = Welcoo Geeksforgeeks
方案3: 这里的指数是负的。
// Java program to illustrate the
// java.lang.StringBuffer.delete()
import java.lang.*;
public class geeks {
public static void main(String[] args)
{
StringBuffer sbf = new StringBuffer("Welcome to Geeksforgeeks");
System.out.println("string buffer = " + sbf);
sbf.delete(-5, 9);
System.out.println("After deletion string buffer is = " + sbf);
}
}
输出:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -5
at java.lang.AbstractStringBuilder.delete(AbstractStringBuilder.java:756)
at java.lang.StringBuffer.delete(StringBuffer.java:430)
at geeks.main(geeks.java:13)
程序4: 这里的索引不存在。
// Java program to illustrate the
// java.lang.StringBuffer.delete()
import java.lang.*;
public class geeks {
public static void main(String[] args)
{
StringBuffer sbf = new StringBuffer("Welcome to Geeksforgeeks");
System.out.println("string buffer = " + sbf);
sbf.delete(99, 109);
System.out.println("After deletion string buffer is = " + sbf);
}
}
输出:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException
at java.lang.AbstractStringBuilder.delete(AbstractStringBuilder.java:760)
at java.lang.StringBuffer.delete(StringBuffer.java:430)
at geeks.main(geeks.java:13)