欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JAVA中字符串函数subString的用法小结

程序员文章站 2024-02-21 10:53:52
string str;str=str.substring(int beginindex);截取掉str从首字母起长度为beginindex的字符串,将剩余字符串赋值给str...

string str;
str=str.substring(int beginindex);截取掉str从首字母起长度为beginindex的字符串,将剩余字符串赋值给str;

str=str.substring(int beginindex,int endindex);截取str中从beginindex开始至endindex结束时的字符串,并将其赋值给str;

demo:

复制代码 代码如下:

class test
{
 public static void main(string[] args)
 {
  string s1 ="1234567890abcdefgh";
  s1 = s1.substring(10);
  system.out.println(s1);
 }
}

运行结果:abcdefgh
复制代码 代码如下:

class test
{
 public static void main(string[] args)
 {
  string s1 ="1234567890abcdefgh";
  s1 = s1.substring(0,9);
  system.out.println(s1);
 }
}

运行结果:123456789

下面是个典型例子:

复制代码 代码如下:

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


运行结果:
this is my string