如何在Java中将下划线转换为人类可读的名称?

时间:2016-09-29 01:18:11

标签: java string

我想编写一个将CamelCase转换为人类可读名称的方法。 这与this question非常相似,但现在使用下划线。

以下是测试用例:

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__"));
}

3 个答案:

答案 0 :(得分:4)

实现这一目标的一种天真的方法是用'_'替换每个' ',然后从最终字符串中删除空格:

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

虽然以上适用于大多数情况,但为了处理多个相邻的下划线,我们可以使用正则表达式用单个' '替换任意数量的连续下划线:

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

答案 1 :(得分:2)

以下内容应该有效:

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

答案 2 :(得分:1)

您应该有更多测试用例:

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__"));