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))

扫描二维码关注公众号,回复: 454400 查看本文章

    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

猜你喜欢

转载自www.cnblogs.com/yuechuan/p/9022514.html