Java中的 StringBuffer deleteCharAt() 方法及示例
Java.lang.StringBuffer.deleteCharAt() 是一种内置的Java方法,用于删除此序列中指定位置的字符。使序列减少 1 个字符。
句法:
public StringBuffer deleteCharAt(int indexpoint)
参数:该方法接受一个整数类型的参数索引点,它指的是要删除的字符的索引。
返回值:函数返回字符串或删除字符后返回此对象。
异常:如果索引点为负数或大于或等于 length(),则该方法抛出StringIndexOutOfBoundsException 。
例子:
Input : StringBuffer = worldofgeeks
int indexpoint = 4
Output : worlofgeeks
下面的程序说明了 StringBuffer.deleteCharAt() 方法的工作:
方案一:
// Java program to demonstrate working
// of StringBuffer.deleteCharAt() method
import java.lang.*;
public class Geeks {
public static void main(String[] args)
{
StringBuffer sbf = new StringBuffer("raghav");
System.out.println("String buffer before deletion = " + sbf);
// Deleting the character at indexpoint 5
sbf.deleteCharAt(5);
System.out.println("After deletion new StringBuffer = " + sbf);
}
}
输出:
String buffer before deletion = raghav
After deletion new StringBuffer = ragha
方案二:
// Java program to demonstrate working
// of StringBuffer.deleteCharAt() method
import java.lang.*;
public class Geeks {
public static void main(String[] args)
{
StringBuffer sbf = new StringBuffer("GeeksforGeeks");
System.out.println("String buffer before deletion = " + sbf);
// Deleting the character at indexpoint 5
sbf.deleteCharAt(5);
System.out.println("After deletion new StringBuffer = " + sbf);
}
}
输出:
String buffer before deletion = GeeksforGeeks
After deletion new StringBuffer = GeeksorGeeks
方案 3:
// Java program to demonstrate working
// of StringBuffer.deleteCharAt() method
import java.lang.*;
public class Geeks {
public static void main(String[] args)
{
StringBuffer sbf = new StringBuffer("Abhishek");
System.out.println("String buffer before deletion = " + sbf);
// Deleting the character at indexpoint -5
sbf.deleteCharAt(-5);
System.out.println("After deletion new StringBuffer = " + sbf);
}
}
输出:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -5
at java.lang.AbstractStringBuilder.deleteCharAt
(AbstractStringBuilder.java:824)
at java.lang.StringBuffer.deleteCharAt(StringBuffer.java:441)
at Geeks.main(Geeks.java:14)