java字符串相关操作(二)
/*5、删除字符串最后一个字符*/ (一)substring() 方法进行截取,0 作为起始下标,length() - 1 public static String removeLastChar(String s) { return (s == null || s.length() == 0) ? null : (s.substring(0, s.length() - 1)); } (二)Apache 的 Commons Lang 包:StringUtils.substring(s, 0, s.length() - 1); (三)StringUtils.chop(s);只删最后一个字符 (四)String result= (s == null) ? null : s.replaceAll(".$", "");正则替换 (五)String result1 = Optional.ofNullable(s) .map(str -> str.replaceAll(".$", "")) .orElse(s);java 8 的 Lambda 表达式和Optional /*6、统计字符在字符串中出现的次数*/ (一)使用最基础的方法 public int count(){ String someString = "chenmowanger"; char someChar = e; int count = 0; for (int i = 0; i < someString.length(); i++) { if (someString.charAt(i) == someChar) { count++; } } } (二)long count = someString.chars().filter(ch -> ch == e).count();java8 (三)int count2 = StringUtils.countMatches("chenmowanger", "e"); 使用Apache 的 Commons Lang 包 /*7、拆分字符串*/ (一)String[] splitted = "范范,像前辈致敬".split(","); (二)String[] splitted = StringUtils.split("范范,像前辈致敬", ",");使用 Apache 的 Commons Lang 包: /*8、字符串比较*/ (一)string1.equals(string2),切记不能使用==
上一篇:
Java基础知识总结(2021版)
下一篇:
小程序(微信和支付宝)面试知识点