String fullname="Mr Vivek N Nandakumar Sr";
String [] strst={"Sr.", "sr.", "Jr.", "jr.","Jr ","jr ","Sr ","sr "," Jr"," jr"," Sr"," sr",",I",".I","I.","II","III"," IV","IV ",".IV",",IV", "V.","V ",".V",",V","VI", "VII", "VIII", "IX", "X" ,"M.D","MBA","PhD","M.A","Mr.","Mr ","Mrs.","Miss","MISS","miss","MR ","MRS ","mr ","mrs "," mr"," mrs","Dr ","DR ","Dr.","DR.",")","("};
我只想从全名中删除此给定的数组字符串。
我希望输出像....“ Vivek N Nandakumar”
答案 0 :(得分:0)
我不知道您使用的Java是什么版本,但是在Java 8中,我将使用类似这样的流:
Arrays.stream(fullname.split(" ")).filter(namePart -> Arrays.stream(strst).noneMatch(str -> str.trim().equals(namePart))).collect(Collectors.joining(" "));
对我来说,输出就如您所愿。
EDIT
JAVA 7就是这种情况。在此之前,您必须实现自己的搜索。
String fullname="Mr Vivek N Nandakumar Sr";
String [] strst={"Sr.", "sr.", "Jr.", "jr.","Jr ","jr ","Sr ","sr "," Jr"," jr"," Sr"," sr",",I",".I","I.","II","III"," IV","IV ",".IV",",IV", "V.","V ",".V",",V","VI", "VII", "VIII", "IX", "X" ,"M.D","MBA","PhD","M.A","Mr.","Mr ","Mrs.","Miss","MISS","miss","MR ","MRS ","mr ","mrs "," mr"," mrs","Dr ","DR ","Dr.","DR.",")","("};
Arrays.sort(strst);
StringBuilder sb = new StringBuilder();
for (String namePart :
fullname.split(" ")) {
if (Arrays.binarySearch(strst, namePart, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.trim().compareTo(o2.trim());
}
}) < 0 ) {
sb.append(namePart).append(" ");
}
}
return sb.toString();
答案 1 :(得分:0)
如果您对空间复杂度没有限制,则尝试在数组中使用空格(如果用空格分隔)来分割主字符串,并检查给定数组中的每个值(如果找到)从主字符串数组中删除该值最后连接主字符串数组。我会说使用set存储第二个列表,它将帮助您提高时间性能。它将把时间从O(n ^ 2)减少到O(n)。