當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。