Java String Capitalize First capitalizedLetter(String str, boolean onlyFirst)

Here you can find the source of capitalizedLetter(String str, boolean onlyFirst)

Description

Capitalized first letter for each words or only first one

License

Open Source License

Parameter

Parameter Description
str String
onlyFirst Only first word letter capitalized

Return

String capitalized

Declaration

public static String capitalizedLetter(String str, boolean onlyFirst) 

Method Source Code

//package com.java2s;
/*//w  w  w .j  av a  2  s. c om
 * movie-renamer-core
 * Copyright (C) 2012 Nicolas Magr?
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Capitalized first letter for each words or only first one
     *
     * @param str
     * String
     * @param onlyFirst
     * Only first word letter capitalized
     * @return String capitalized
     */
    public static String capitalizedLetter(String str, boolean onlyFirst) {
        StringBuilder res = new StringBuilder();
        char ch, prevCh;
        boolean toUpper = true;
        prevCh = '.';
        str = str.toLowerCase();
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);
            if (ch == 's' && prevCh == '\'') {
                res.append(ch);
            } else if (toUpper && Character.isLetter(ch)) {
                if (!Character.isLetter(prevCh) || (prevCh == 'i' && ch == 'i')) {
                    res.append(Character.toUpperCase(ch));
                    if (onlyFirst) {
                        toUpper = false;
                    }
                } else {
                    res.append(ch);
                }
            } else {
                res.append(ch);
            }

            prevCh = ch;
        }
        return res.toString();
    }
}

Related

  1. capitaliseFirstLetter(String s)
  2. capitaliseFirstLetter(String str)
  3. capitaliseFirstLetter(String str)
  4. capitaliseFirstLetter(String text)
  5. capitalizedFirst(String str)
  6. capitalizeFirst(String attribute)
  7. capitalizeFirst(String input)
  8. capitalizeFirst(String name)
  9. capitalizeFirst(String rawStr)