我正在研究一种方法,该方法将一个字符串数组作为输入,并返回一个仅包含大写字母的缩略语数组。
例如:
[United Nations, United Federation of Planets, null, , ignore me] -> [UN, UFP, null, , ]
由于某种原因,我的代码没有返回任何内容,它还向我显示空检查是一个死代码,我无法弄清楚原因。
public static String[] convertStringsToAcronyms(String[] input)
{
int itemCount = input.length;
String[] result = new String[itemCount];
int k = 0;
for (String words : input) {
boolean checklowercase = words.toLowerCase().equals(words);
if (checklowercase || (words == ""))
result[k] = "";
if (words == null)
result[k] = null;
String add = "";
String[] ary = words.split("");
for (String letter : ary) {
char firstletter = letter.charAt(0);
if (Character.isUpperCase(firstletter))
add = add + firstletter;
}
result[k] = add;
k++;
add = "";
}
return result;
}
答案 0 :(得分:1)
null检查是死代码,因为在它之前你访问words
变量,所以如果它是null,你将在null检查之前得到NullPointerException
。 / p>
boolean checklowercase = words.toLowerCase().equals(words);
....
if (words == null) // this can never be true
result[k] = null; // this is dead code
答案 1 :(得分:1)
我认为这样可以做得更优雅。
public static sampleAcronymMethod()
{
String[] arr = {"United Nations", "United Federation of Planets"};
for (String element : arr) //go through all of our entries we wish to generate acronyms for
{
String[] splits = element.split("[a-z]+");//remove all lowercase letters via regular expression
String acronym = "";//start with an empty acronym
for (String split : splits)//go through our uppercase letters for our current array entry in arr
acronym = acronym + split;//tack them together
acronym = acronym.replaceAll("\\s","");//remove whitespace
System.out.println("Acronym for " + element + " is " + acronym);
}
}
答案 2 :(得分:0)
Java 1.8中更优雅
String[] i = new String[] {"United Nations", "United Federation of Planets", null, "", "ignore me"};
String[] array = Arrays.stream(i)
.filter(it -> it != null && !it.isEmpty())
.map(it -> it.split(" "))
.map(words -> Arrays.stream(words)
.map(w -> w.substring(0, 1))
.filter(l -> l.toUpperCase().equals(l))
.collect(Collectors.joining()))
.toArray(String[]::new);
System.out.println(Arrays.toString(array));