Whitecat
Whitecat

Reputation: 4020

How do I convert underscore into human-readable names in Java?

I'd like to write a method that converts CamelCase into a human-readable name. This is very similar to this question but now with underscore.

Here's the test case:

public void testSplitUnderscore() {
    assertEquals("lowercase", splitUnderscore("lowercase"));
    assertEquals("Class", splitUnderscore("Class"));
    assertEquals("My Class", splitUnderscore("My_Class"));
    assertEquals("HTML", splitUnderscore("HTML"));
    assertEquals("PDF Loader", splitUnderscore("PDF_Loader"));
    assertEquals("A String", splitUnderscore("A_String"));
    assertEquals("Simple XML Parser", splitUnderscore("Simple_XML_Parser"));
    assertEquals("GL 11 Version", splitUnderscore("GL_11_Version"));
    assertEquals("99 Bottles", splitUnderscore("99_Bottle"));
    assertEquals("May 5", splitUnderscore("May_5"));
    assertEquals("BFG 9000", splitUnderscore("BFG_9000"));
    assertEquals("beginning", splitUnderscore("_beginning"));
    assertEquals("end", splitUnderscore("end_"));
    assertEquals("double middle", splitUnderscore("double__middle"));
    assertEquals("double end", splitUnderscore("double_end__"));
    assertEquals("double start", splitUnderscore("__double_start"));
    assertEquals("double start middle end", splitUnderscore("__double_start__middle_end__"));
}

Upvotes: 0

Views: 839

Answers (3)

Matthew Diana
Matthew Diana

Reputation: 1106

A naive way of accomplishing this would be to replace every '_' with a ' ', and then trim the whitespaces off the final string:

public static String splitUnderscore(String s) {
    return s.replace("_", " ").trim();
}

While the above works for most cases, to handle multiple adjacent underscores we could use a regular expression to replace any number of consecutive underscores with a single ' ':

public static String splitUnderscore(String s) {
    return s.replaceAll("_{1,}", " ").trim();
}

Upvotes: 4

Graham H
Graham H

Reputation: 157

You should have a couple more test cases:

assertEquals("A String", splitUnderscore("double__middle"));
assertEquals("A String", splitUnderscore("double_end__"));
assertEquals("A String", splitUnderscore("__double_start"));
assertEquals("A String", splitUnderscore("__double_start__middle_end__"));

Upvotes: 1

Mr. Negi
Mr. Negi

Reputation: 154

The following should work:

String.replace('_', " ").trim();

Upvotes: 2

Related Questions