Home > Enterprise >  Get acronym from string Java
Get acronym from string Java

Time:05-28

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?

CodePudding user response:

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 == '#';
    }
}

CodePudding user response:

Not really shorter but a regex approach:

public static void getAcronym(String str) {
    Pattern.compile("\\b[A-Za-z]")
           .matcher(str)
           .results()
           .map(MatchResult::group)
           .forEach(System.out::print);
}

CodePudding user response:

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();
}

CodePudding user response:

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());
}
  •  Tags:  
  • java
  • Related