Java StringBuffer deleteCharAt()方法及实例
Java.lang.StringBuffer.deleteCharAt()是一个内置的Java方法,它可以删除这个序列中指定位置上的字符。这样,该序列就减少了1个字符。
语法
public StringBuffer deleteCharAt(int indexpoint)
参数: 该方法接受一个整数类型的参数indexpoint,它指的是要删除的字符的索引。
返回值: 该函数返回字符串或在删除字符后返回这个对象。
异常: 如果indexpoint是负数或大于等于length(),那么该方法抛出StringIndexOutOfBoundsException。
例子
Input : StringBuffer = worldofgeeks
int indexpoint = 4
Output : worlofgeeks
下面的程序说明了StringBuffer.deleteCharAt()方法的工作情况:
程序1 :
// 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
程序2
// 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)