Rewrite capitalize method

This commit is contained in:
atomicint
2015-04-07 18:58:58 -04:00
parent 725ada7878
commit 6ada19fdc4
+15 -24
View File
@@ -2,7 +2,7 @@ package org.apollo.util;
/** /**
* A class which contains text-related utility methods. * A class which contains text-related utility methods.
* *
* @author Graham * @author Graham
*/ */
public final class TextUtil { public final class TextUtil {
@@ -18,37 +18,28 @@ public final class TextUtil {
/** /**
* Capitalizes the string correctly. * Capitalizes the string correctly.
* *
* @param str The input string. * @param str The input string.
* @return The string with correct capitalization. * @return The string with correct capitalization.
*/ */
public static String capitalize(String str) { public static String capitalize(String str) {
char[] chars = str.toCharArray(); boolean capitalize = true;
boolean sentenceStart = true; StringBuilder bldr = new StringBuilder(str);
for (int i = 0; i < chars.length; i++) { for (int index = 0, length = str.length(); index < length; index++) {
char c = chars[i]; char character = bldr.charAt(index);
if (sentenceStart) { if (character == '.' || character == '!' || character == '?') {
if (c >= 'a' && c <= 'z') { capitalize = true;
chars[i] -= 0x20; } else if (capitalize && !Character.isWhitespace(character)) {
sentenceStart = false; bldr.setCharAt(index, Character.toUpperCase(character));
} else if (c >= 'A' && c <= 'Z') { capitalize = false;
sentenceStart = false;
}
} else {
if (c >= 'A' && c <= 'Z') {
chars[i] += 0x20;
}
}
if (c == '.' || c == '!' || c == '?') {
sentenceStart = true;
} }
} }
return new String(chars, 0, chars.length); return bldr.toString();
} }
/** /**
* Compresses the input text ({@code in}) and places the result in the {@code out} array. * Compresses the input text ({@code in}) and places the result in the {@code out} array.
* *
* @param in The input text. * @param in The input text.
* @param out The output array. * @param out The output array.
* @return The number of bytes written to the output array. * @return The number of bytes written to the output array.
@@ -95,7 +86,7 @@ public final class TextUtil {
/** /**
* Filters invalid characters from the specified string. * Filters invalid characters from the specified string.
* *
* @param str The input string. * @param str The input string.
* @return The filtered string. * @return The filtered string.
*/ */
@@ -115,7 +106,7 @@ public final class TextUtil {
/** /**
* Uncompresses the compressed data ({@code in}) with the length ({@code len}) and returns the uncompressed * Uncompresses the compressed data ({@code in}) with the length ({@code len}) and returns the uncompressed
* {@link String}. * {@link String}.
* *
* @param in The compressed input data. * @param in The compressed input data.
* @param len The length. * @param len The length.
* @return The uncompressed {@link String}. * @return The uncompressed {@link String}.