startsWith(),endsWith()的作用,用法,判断字符串a 是不是以字符串b开头或结尾

 

Java代码

startsWith:

  • if(a.startsWith(b))
  • //判断字符串a 是不是以字符串b开头.

endsWith:

  • if(a.endsWith(b))
  • //判断字符串a 是不是以字符串b结尾.

JAVA例子

1. public class StringDemo{ 

  1. public class startsWith {
  2.         public static void main(String args[]){ 
  3.          String s1="this is my startsWith string"; 
  4.          String sd="startsWith"; 
  5.          if (s1.startsWith(sd))  
  6.              //startsWith()方法判断字符串s1是否从字符串sd开始 
  7.              s1=s1.substring(sd.length()); 
  8.          else 
  9.              if(s1.endsWith(sd))  
  10.                    //endWith()方法判断字符串s1是否从字符串sd结尾 
  11.                   s1=s1.substring(0,s1.length()-sd.length()); 
  12.              else 
  13.              { 
  14.                    int index=s1.indexOf(sd);  
  15.                   //indexOf()搜索字符或子字符串首次出现,这里的index等于11 
  16.                   if(index!=-1) 
  17.                    { 
  18.                       String s2=s1.substring(0,index);  
  19.                        //从字符串s1的首字符开始,取index个字符 
  20.                        String s3=s1.substring(index+sd.length());  
  21.                        //取字符串s1的第19个字符后面的字符串 
  22.                        s1=s2+s3; 
  23.                    } 
  24.                    else 
  25.                        System.out.println("string \""+sd+"\" not found"); 
  26.               } 
  27.           System.out.println(s1); 
  28.          } 
  29.   
  30. }

   输出结果:this is my  string

 

posted @ 2017-04-08 09:41  彼岸辰星  阅读(1253)  评论(0编辑  收藏  举报