Get acronym from string Java

Viewed 71

Should be pretty self-explanatory.

public class Main
{
    public static void main(String[] args) {
        String str = "Get#the#Acronym";
        getAcronym(str);
    }
    
    public static void getAcronym(String str){
        String[] parts = str.split("#");
        for(var item : parts){
            char a = item.charAt(0);
            System.out.print(a);
        }
    }
}

I've already solved it this way, but was wondering if there is a shorter way without regex?

3 Answers

Here is a simple one that avoids regex. It would handle duplicated # different from yours.

public static void getAcronym(String str){
    boolean isInAcronym = true;
    for(char c : str.toCharArray()) {
        if (isInAcronym) {
            System.out.print(c);
        }
        isInAcronym = c == '#';
    }
}

You could also stream the split and combine it via StringBuilder before returning or printing it.

public static String getAcr(String str) {
    StringBuilder sb = new StringBuilder();
    Arrays.stream(str.split("#"))
            .forEach(part -> sb.append(part.charAt(0)));
    return sb.toString();
}

You could return the acronym like this:

public String getAcronym(String str) {
    return Arrays.stream(str.split("#")).map(s -> s.substring(0, 1)).collect(Collectors.joining());
}
Related