字符串最经常使用的三个处理方法(常常记错记混,特此mark一下):java
indexOf()正则表达式
java.lang.String.indexOf() 的用途是在一个字符串中寻找一个字的位置,同时也能够判断一个字符串中是否包含某个字符,返回值是下标,没有则是-1;3d
String str1 = "abcdefg"; int result1 = str1.indexOf("ab"); if(result1 != -1){ System.out.println("字符串str中包含子串“ab”"+result1); }else{ System.out.println("字符串str中不包含子串“ab”"+result1); }
substring()code
根据下标截取字符串字符串
String str="Hello world!" System.out.println(str.substring(3)); 输出:lo world! (一个参数表明截取这个从这个下标开始到以后的内容)
String str="Hello world!" System.out.println(str.substring(3,7)) 输出:lo w (截取下标从3开始,到7以前的字符串)
split()string
将字符串按特定字符分割(特殊字符须要转义:split("\\|"),split("\\*"))it
String abc="a,b,c,e"; String[] a=abc.split(","); for(String t:a){ System.out.println(t); } 输出:a b c e (按逗号分隔)
replace() 、replaceAll()、replaceFirst()方法
replace 的参数是char和CharSequence,便可以支持字符的替换,也支持字符串的替换(CharSequence即字符串序列的意思,说白了也就是字符串) replaceAll 的参数是regex,即基于正则表达式的替换,好比,能够经过replaceAll("\\d", "*")把一个字符串全部的数字字符都换成星号;replaceFirst() 替换第一次出现的这个方法也是基于规则表达式的替换:co
String src = new String("ab43a2c43d"); System.out.println(src.replace("3","f"));=>ab4f2c4fd. System.out.println(src.replace('3','f'));=>ab4f2c4fd. System.out.println(src.replaceAll("\\d","f"));=>abffafcffd. System.out.println(src.replaceAll("a","f"));=>fb43fc23d. System.out.println(src.replaceFirst("\\d,"f"));=>abf32c43d System.out.println(src.replaceFirst("4","h"));=>abh32c43d.