Trouble Converting a String to Acronyms

1.7k views Asked by At

I'm working on a method which gets as an input an array of Strings and returns an array of its Acronyms that are only capital letters.

For example:

[United Nations,  United Federation of Planets, null, , ignore me] -> [UN, UFP, null, , ]

For some reason my code does not return anything, and it also shows me that the null check is a dead code and I can't figure out why.

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;

}
3

There are 3 answers

0
Eran On

The null check is dead code because prior to it you access the words variable, so if it's null, you'll get a NullPointerException before the null check.

boolean checklowercase = words.toLowerCase().equals(words);
....
if (words == null) // this can never be true
    result[k] = null; // this is dead code
2
Alexander Kohler On

I think this will do what you're after a little more elegantly.

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);
   }
}
0
vrudkovsk On

Yet more elegant in 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));