Java中根据特定字符截取字符串的方法


1、String的substring()方法:根据索引截取

  //截取从下标begin到str.length()-1内容
  substring(begin) 
  //截取指定范围的内容
  substring(begin,end)

举个栗子:

  
  String str = "abc_def_Ghi";   //索引0~10

  //截取以下标2元素开始余下的字符
  System.out.println(str.substring(1));    //bc_def_Ghi(含1的位置)

  //从下标为3的位置开始截取,到5个位置停止截取,结果不包括5
  System.out.println(str.substring(3,5));  //_d

2、String的indexof():返回一个整数值,即索引位置

        String s = "abc_def_Ghi";//0~10
        // int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。        
        //从头开始查找是否存在指定的字符
        System.out.println(s.indexOf("c"));     //2
        //int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。
        // 从索引为3位置开始往后查找,包含3的位置
        System.out.println(s.indexOf("d", 3));  //4
        //若指定字符串中没有该字符则系统返回-1
        System.out.println(s.indexOf("A"));     //-1
        //int lastIndexOf(String str) 从后往前找一次出现的位置
        System.out.println(s.lastIndexOf("_")); //7

灵活运用这两个方法,可以进行多样的操作

(1)获取第一个"_"及后面所有字符,举例:

String a = "abc_def_Ghi";
int index = a.indexOf("_");//获取第一个"_"的位置3
String str1 = a.substring(index);//含"_"
System.out.println("第一个_及后面字符串为:" + str1);//_def_Ghi

(2)获取第一个"_"前面所有字符,举例:

String a = "abc_def_Ghi";
int index = a.indexOf("_");//获取第一个"_"的位置3
String str2 = a.substring(0,index);//不含"_",这叫含头不含尾
System.out.println("第一个_前面字符串为:" + str2 );//abc

(3)获取第二个"_"及后面所有字符,举例:

String a = "abc_def_Ghi";
String str3 = a.substring(a.indexOf("_",a.indexOf("_") + 1));//包含本身位置
System.out.println("第二个_及后面字符串为:" + str3 );//_Ghi

(4)获取第二个"_"前面所有字符,举例:

String a = "abc_def_Ghi";
String str4 = a.substring(0,a.indexOf("_",a.indexOf("_") + 1));//不包含本身位置
System.out.println("第二个_前面字符串为:" + str4 );//abc_def

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM