0

I want to programmatically capitalize words in a String depending on a dictionary (!). It should be like the Java variable and method naming conventions in CamelCase. Given is a string in all lowercase. Find the most likely Java convention casing.

I made a start here with an existing dictionary file and a class for checking whether a given String is part of the dictionary or not. The difficulty is to find the right or most likely substrings. How would you improve this?

public String capitalizeWords(String text)
{
    text = text.toLowerCase();
    StringBuilder capitalizedWordBuilder = new StringBuilder();

    int firstWordLength = text.length();
    int beginIndex = 0;

    while (true)
    {
        String subText = text.substring(beginIndex, firstWordLength);

        if (contains(subText))
        {
            String word = capitalizeFirst(subText);
            capitalizedWordBuilder.append(word);
            beginIndex += word.length();
            firstWordLength = text.length() + 1;
        }

        firstWordLength--;

        if (beginIndex == firstWordLength && beginIndex == text.length())
        {
            String capitalized = capitalizedWordBuilder.toString();
            return deCapitalizeFirst(capitalized);
        }
    }
}

private String capitalizeFirst(String text)
{
    if (text.length() < 2)
    {
        return text;
    }

    return Character.toUpperCase(text.charAt(0)) + text.substring(1);
}

private String deCapitalizeFirst(String text)
{
    if (text.length() < 2)
    {
        return text;
    }

    return Character.toLowerCase(text.charAt(0)) + text.substring(1);
}

Example runs:
javaisawesome -> javaIsAwesome (Good)
thisisastring -> thisIsAstrIng (Bad)

Community
  • 1
  • 1
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185

0 Answers0