题目
Help! THB has gone missing, and we need you to find him! You will be given a string, and must return a string including only the t's, h's, and b's from the original string. Include both uppercase and lowercase.
Remember, you should return an empty string if you are given an empty string or a null string. Good luck!
解析
救命!THB失踪了,我们需要你找到他!您将得到一个字符串,并且必须返回一个仅包含原始字符串的T、H和B的字符串。包括大写和小写。
请记住,如果给定空字符串或空字符串,则应返回空字符串。祝你好运!
本题主要考察字符串和字符间的转换
我的答案
public static String testing(String initial) {
if(("").equals (initial)||initial==null){
return "";
}
List list = new ArrayList();
for (int i = 0;i<initial.length();i++){
char item = initial.charAt(i);
if(item=='t'||item=='T'){
list.add(item);
}else if(item=='h'||item=='H'){
list.add(item);
}else if(item=='b'||item=='B'){
list.add(item);
}
}
String str2 = StringUtils.join(list.toArray(),"");//将将逗号去掉,
return str2;
}
最优答案
static String testing(final String initial) {
if (initial == null) {
return "";
}
return initial.replaceAll("[^TBHtbh]", "");//通过正则表达式匹配
}