Java String Title Case toTitleCase(final String s)

Here you can find the source of toTitleCase(final String s)

Description

Converts an input string into title case, capitalizing the first character of every word.

License

Open Source License

Parameter

Parameter Description
s input string

Return

string transformed into title case

Declaration

public static String toTitleCase(final String s) 

Method Source Code

//package com.java2s;
/* Copyright (c) 2011-2013 Pushing Inertia
 * All rights reserved.  http://pushinginertia.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.//www.j av  a2  s.c  o  m
 */

public class Main {
    private static final String WORD_SEPARATORS = " .-_/()";

    /**
     * Converts an input string into title case, capitalizing the first character of every word.
     * @param s input string
     * @return string transformed into title case
     */
    public static String toTitleCase(final String s) {
        final StringBuilder sb = new StringBuilder(s);
        return toTitleCase(sb).toString();
    }

    private static StringBuilder toTitleCase(final StringBuilder sb) {
        boolean capitalizeNext = true;
        for (int i = 0; i < sb.length(); i++) {
            final char c = sb.charAt(i);
            if (isSeparator(c)) {
                capitalizeNext = true;
            } else if (capitalizeNext) {
                sb.setCharAt(i, Character.toTitleCase(c));
                capitalizeNext = false;
            } else if (!Character.isLowerCase(c)) {
                sb.setCharAt(i, Character.toLowerCase(c));
            }
        }
        return sb;
    }

    private static boolean isSeparator(char c) {
        return WORD_SEPARATORS.indexOf(c) >= 0;
    }
}

Related

  1. titleCaseTruncate(String s, int maxlen)
  2. toTitleCase(final int chr)
  3. toTitleCase(final String input)
  4. toTitleCase(final String inStr)
  5. toTitleCase(final String inStr, final boolean putRestInLC)
  6. toTitleCase(final String text)
  7. toTitleCase(String givenString)
  8. toTitleCase(String input)
  9. toTitleCase(String input, boolean eachWord)