Convert a String to Proper Name Case

Return a String converted to Proper Name case (also referred to as Title Case).

Javadoc available at https://www.javatapas.com/docs/javatapas/string/ProperNameCase.html


public static String properNameCase(String str) {

	if (str == null){return str;}

	str = str.trim();

	StringBuffer sb=new StringBuffer();

	boolean cap = true;

	for (int i = 0; i < str.length(); i++) {

		if (!cap && str.charAt(i) != ':') {sb.append(Character.toLowerCase(str.charAt(i)));}

		if (cap && str.charAt(i) != ':') {sb.append(Character.toUpperCase(str.charAt(i)));}

		cap = false;

		if(str.charAt(i) == ' ' || // La pierre -> La Pierre
  		   str.charAt(i) == '-' || // Smith-williams -> Smith-Williams
  		   str.charAt(i) == '.' || // St. stephens -> St. Stephens
		   (str.charAt(i) == '\'' &&  // start Steven'S -> Steven's or D'arcy -> D'Arcy
				(
					(i < str.length() - 2 && (Character.toUpperCase(str.charAt(i+1)) != 'S' ||
	   									 	 (Character.toUpperCase(str.charAt(i+1)) == 'S' && str.charAt(i+2) != ' '))) ||
					(i == str.length() - 2)
		   		)
		   	) || // end 's Steven'S -> Steven's
		   ( // start Mcneil -> McNeil
			   (i == 1 || (i > 1 && str.charAt(i-2) == ' ')) &&
		   		Character.toUpperCase(str.charAt(i)) == 'C' &&
	   			Character.toUpperCase(str.charAt(i-1)) == 'M'
	   			) // end Mc
	   		) // end Top if
  		  {cap = true;}

	}  // end for

	return sb.toString();

}