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

String customerAddress = "城西-4号楼-1-0801";
//得到索引的位置
int index = customerAddress.indexOf("-");
// 获取第一个"_"前面所有字符
String communityName = customerAddress.substring(0,index);
//获取第一个"_"后面所有字符
String roomCode= customerAddress.substring(index+1);
                                
                              
获取第二个"_"及后面所有字符,举例:

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

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

用到的方法:

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

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

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

你可能感兴趣的:(笔记,java)