Java中substring的使用方法

发表于:2015-6-10 10:14

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:lcchuguo    来源:51Testing软件测试网采编

  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);
}
}
  补充: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。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号