Close

Java - How to convert camel case or Java identifier to a displayable string?

[Last Updated: May 18, 2018]

Java String Manipulation Java 

Following example shows how to convert camel case string to a displayable (space separated) string. This also works for Java identifiers (method, field, class names)

package com.logicbig.example;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;

public class DisplayableStrings {
    //to split camel case
    public static String[] splitByCapitalLetters(String input) {
        return input.split("(?=\\p{Upper})");
    }

    public static String fromJavaIdentifierToDisplayableString(String input) {
        String rv = "";
        for (String s : splitByCapitalLetters(input)) {
            rv += s + " ";
        }
        rv = rv.trim();
        if (Character.isLowerCase(rv.charAt(0))) {
            rv = Character.toUpperCase(rv.charAt(0)) + rv.substring(1, rv.length());
        }
        return rv;
    }

    public static void main(String[] args) {
        String s = fromJavaIdentifierToDisplayableString(BigDecimal.class.getSimpleName());
        System.out.println(s);
        Arrays.stream(ArrayList.class.getDeclaredMethods()).map(Method::getName)
              .forEach(f -> {
                  System.out.println(f + " -> " + fromJavaIdentifierToDisplayableString(f));
              });
    }
}
Big Decimal
add -> Add
add -> Add
add -> Add
remove -> Remove
remove -> Remove
get -> Get
clone -> Clone
indexOf -> Index Of
clear -> Clear
isEmpty -> Is Empty
lastIndexOf -> Last Index Of
contains -> Contains
replaceAll -> Replace All
size -> Size
subList -> Sub List
toArray -> To Array
toArray -> To Array
iterator -> Iterator
spliterator -> Spliterator
addAll -> Add All
addAll -> Add All
set -> Set
access$000 -> Access$000
readObject -> Read Object
writeObject -> Write Object
forEach -> For Each
newCapacity -> New Capacity
ensureCapacity -> Ensure Capacity
trimToSize -> Trim To Size
hugeCapacity -> Huge Capacity
retainAll -> Retain All
removeAll -> Remove All
removeIf -> Remove If
removeIf -> Remove If
sort -> Sort
listIterator -> List Iterator
listIterator -> List Iterator
removeRange -> Remove Range
rangeCheckForAdd -> Range Check For Add
outOfBoundsMsg -> Out Of Bounds Msg
outOfBoundsMsg -> Out Of Bounds Msg
elementData -> Element Data
grow -> Grow
grow -> Grow
elementAt -> Element At
fastRemove -> Fast Remove
shiftTailOverGap -> Shift Tail Over Gap
batchRemove -> Batch Remove
nBits -> N Bits
setBit -> Set Bit
isClear -> Is Clear
checkInvariants -> Check Invariants

See Also