java中substring的用法


java中substring的用法

 

str=str.substring(int beginIndex);截取掉str從首字母起長度為beginIndex的字符串,將剩余字符串賦值給str;

str=str.substring(int beginIndex,int endIndex);截取str中從beginIndex開始至endIndex結束時的字符串,並將其賦值給str;

以下是一段演示程序:

public class StringDemo{

public static void main(String agrs[]){

   String str="this is my original string";

   String toDelete=" original";

  

   if(str.startsWith(toDelete))

    str=str.substring(toDelete.length());

   else

    if(str.endsWith(toDelete))

     str=str.substring(0, str.length()-toDelete.length());

    else

    {

     int index=str.indexOf(toDelete);

     if(index!=-1)

     {

      String str1=str.substring(0, index);

      String str2=str.substring(index+toDelete.length());

      str=str1+str2;

     }

     else

      System.out.println("string /""+toDelete+"/" not found");

    }

   System.out.println(str);

}

}

(原文引用自:http://hi.baidu.com/ccsos/blog/item/42ff84afe6e62bcd7dd92a62.html)

補充:str=str.substring(int beginIndex,int endIndex);中最終得到的值:

         beginIndex =< str的值 < endIndex

 

 

 

 

 

 

以上補充內容是我自己以前的一點理解

近日在API中看到對它的注解,

把它發布在下面以便更多的和我一樣的初學者更好的理解上面的程序

substring

public  substring(int beginIndex,
                        int endIndex)
返回一個新字符串,它是此字符串的一個子字符串。該子字符串從指定的  beginIndex 處開始,一直到索引  endIndex - 1處的字符。因此,該子字符串的長度為  endIndex-beginIndex

示例:

 "hamburger".substring(4, 8) returns "urge"
 "smiles".substring(1, 5) returns "mile"
 

 

參數:
beginIndex - 開始處的索引(包括)。
endIndex - 結束處的索引(不包括)。
返回:
指定的子字符串。
拋出:
IndexOutOfBoundsException - 如果  beginIndex 為負,或  endIndex 大於此  String 對象的長度,或  beginIndex 大於  endIndex


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM