Java String类的replaceAll方法
代码勇士真题:
给定一个字符串由a-z字母组成的字符串s,长度任意字母可任意组合。
要求编写函数找出s中不在a-m范围内的字母个数n,要求函数返回字符串格式为:n/s的长度
例如:
s="aaabbbbhaijjjm"
error_printer(s) => "0/14"
s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"
public class Printer {
public static String printerError(String s) {
if(s.length()==0){
return "";
}else{
StringBuffer pattern = new StringBuffer("abcdefghijklm");
char[] chr = s.toCharArray();
int errorCount=0;
for(char c:chr){
if(pattern.indexOf(String.valueOf(c))<0){
errorCount++;
}
}
//return "\""+errorCount+"/"+s.length()+"\"";
return String.format("%d/%d",errorCount,s.length());
}
}
public static String printerErrorBest(String s) {
return s.replaceAll("[a-m]", "").length() + "/" + s.length();
}
public static void main(String[] args) {
System.out.println(printerError("aaabbbbhaijjjm"));
}
}
说明:
public String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given
regular expression with the given replacement.
使用replacement参数替换源字符串中所有满足正则表达式的子字符串。