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 String 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
原文地址:https://www.cnblogs.com/mengfanrong/p/3915999.html