当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java StringBuffer deleteCharAt()用法及代码示例


Java.lang.StringBuffer.deleteCharAt()是内置 Java方法,该方法删除此序列中指定位置的char。这样该序列减少了1个字符。

用法:

public StringBuffer deleteCharAt(int indexpoint)

参数:该方法接受整数类型的单个参数索引点,该索引点指向要删除的char的索引。
返回值:该函数返回字符串或删除字符后返回此对象。
异常:如果索引点为负或大于或等于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)


相关用法


注:本文由纯净天空筛选整理自ankita_chowrasia大神的英文原创作品 StringBuffer deleteCharAt() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。