27 Useful String Utility Methods

In this article, we will learn the useful String utility methods. You can use these String utility methods in your day-to-day project work. This post provides a list of 27 useful and commonly used String utility methods.

I frequently use these String utility methods in my day-to-day project work and I thought I have to create an article on this so that everyone can get help from it.

Utility methods perform common, often reused functions and they don't require to have object-level state, that is they tend to be global functions.
As we know that Java provides built-in functions to handle String operations but there are a few more things we do on a regular basis and can be reused. In this post, we will discuss commonly used and may be helpful to keep handy as StringUtil class with static methods.

Empty Checks Methods

1. isEmpty(CharSequence cs)

Checks if a CharSequence is empty ("") or null.
public static boolean isEmpty(final CharSequence cs) {
     return cs == null || cs.length() == 0;
}
JUnit test case for the above method:
@Test
public void isEmptyTest() {
    assertTrue(isEmpty(null));
    assertTrue(isEmpty(""));
    assertFalse(isEmpty(" "));
    assertFalse(isEmpty("bob"));
    assertFalse(isEmpty("  bob  "));
}

2. isNotEmpty(final CharSequence cs)

Checks if a CharSequence is not empty ("") and not null.
public static boolean isNotEmpty(final CharSequence cs) {
     return !isEmpty(cs);
}

public static boolean isEmpty(final CharSequence cs) {
     return cs == null || cs.length() == 0;
}
Note that isNotEmpty() internally made a call to isEmpty() method.

3. isAnyEmpty(final CharSequence... css)

Checks if any of the CharSequences are empty ("") or null.
public static boolean isAnyEmpty(final CharSequence... css) {
     if (css != null && css.length == 0) {
           return false;
     }
     for (final CharSequence cs : css){
        if (isEmpty(cs)) {
             return true;
        }
     }
     return false;
}
Note that isAnyEmpty() internally made a call to isEmpty() method. JUnit test case for isAnyEmpty(final CharSequence... css) method:
@Test
public void isAnyEmptyTest() {
    assertTrue(isAnyEmpty((String) null));   
    assertFalse(isAnyEmpty((String[]) null));
    assertTrue(isAnyEmpty(null, "foo"));
    assertTrue(isAnyEmpty("", "bar"));   
    assertTrue(isAnyEmpty("bob", ""));     
    assertTrue(isAnyEmpty("  bob  ", null)); 
    assertFalse(isAnyEmpty("foo", "bar"));    
    assertFalse(isAnyEmpty(new String[]{}));  
    assertTrue(isAnyEmpty(new String[]{""}));
}

4. isBlank(final CharSequence cs)

Checks if a CharSequence is empty (""), null or whitespace only. This method is similar to isEmpty()but additionally checks for whitespace.
public static boolean isBlank(final CharSequence cs) {
    int strLen;
    if (cs == null || (strLen = cs.length()) == 0) {
         return true;
    }
    for (int i = 0; i < strLen; i++) {
         if (!Character.isWhitespace(cs.charAt(i))) {
             return false;
         }
    }
    return true;
}
JUnit test case for isBlank(final CharSequence cs) method:
@Test
public void isBlankTest() {
    assertTrue(isBlank(null));
    assertTrue(isBlank(""));
    assertTrue(isBlank(" "));
    assertFalse(isBlank("bob"));
    assertFalse(isBlank("  bob  "));
}

5. isNotBlank(final CharSequence cs)

Checks if a CharSequence is not empty (""), not null, and not whitespace only.
public static boolean isNotBlank(final CharSequence cs) {
    return !isBlank(cs);
}
Note that this method internally made a call to the isBlank() method.

6. isAnyBlank(final CharSequence... css)

Checks if any of the CharSequences are empty ("") or null or whitespace only.
public static boolean isAnyBlank(final CharSequence... css) {
     if (css != null && css.length == 0) {
        return false;
     }
     for (final CharSequence cs : css){
        if (isBlank(cs)) {
             return true;
        }
     }
     return false;
}
JUnit test case for this method:
@Test
public void isAnyBlankTest() {
    assertFalse(isAnyBlank((String[]) null));
    assertTrue(isAnyBlank((String) null));
    assertTrue(isAnyBlank(null, "foo"));
    assertTrue(isAnyBlank(null, null));
    assertTrue(isAnyBlank("", "bar"));
    assertTrue(isAnyBlank("bob", ""));
    assertTrue(isAnyBlank("  bob  ", null));
    assertTrue(isAnyBlank(" ", "bar"));
    assertFalse(isAnyBlank(new String[] {}));
    assertTrue(isAnyBlank(new String[] { "" }));
    assertFalse(isAnyBlank("foo", "bar"));
}

Check for Whitespace

7. containsWhitespace(CharSequence seq)

Check whether the given CharSequence contains any whitespace characters.
Whitespace is defined by Character.isWhitespace(char).
Returns true if the CharSequence is not empty and contains at least 1 (breaking) whitespace character
public static boolean containsWhitespace(final CharSequence seq) {
    if (isEmpty(seq)) {
         return false;
    }
    final int strLen = seq.length();
    for (int i = 0; i < strLen; i++) {
        if (Character.isWhitespace(seq.charAt(i))) {
             return true;
        }
    }
    return false;
}
JUnit Test Case:
@Test
public void testContainsWhitespace() {
    assertFalse(containsWhitespace(null));
    assertFalse(containsWhitespace(""));
    assertFalse(containsWhitespace("a"));
    assertFalse(containsWhitespace("abc"));
    assertTrue(containsWhitespace(" "));
    assertTrue(containsWhitespace(" a"));
    assertTrue(containsWhitespace("abc "));
    assertTrue(containsWhitespace("a b"));
    assertTrue(containsWhitespace("a  b"));
}

Trim Methods

8. trimArrayElements( String[] array)

Trim the elements of the given String array, calling String.trim() on each of them.
/**
 * Trim the elements of the given {@code String} array,
 * calling {@code String.trim()} on each of them.
 * @param array the original {@code String} array
 * @return the resulting array (of the same size) with trimmed elements
 */
public static String[] trimArrayElements( String[] array) {
    if (isEmpty(array)) {
         return new String[0];
    }

    String[] result = new String[array.length];
    for (int i = 0; i < array.length; i++) {
         String element = array[i];
         result[i] = (element != null ? element.trim() : null);
    }
    return result;
}

9. trimWhitespace(String str)

Trim leading and trailing whitespace from the given String.
/**
 * Trim leading and trailing whitespace from the given {@code String}.
 * @param str the {@code String} to check
 * @return the trimmed {@code String}
 * @see java.lang.Character#isWhitespace
 */
public static String trimWhitespace(String str) {
    if (!hasLength(str)) {
         return str;
    }

    int beginIndex = 0;
    int endIndex = str.length() - 1;

    while (beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex))) {
         beginIndex++;
    }

    while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) {
         endIndex--;
    }

    return str.substring(beginIndex, endIndex + 1);
}
JUnit test case:
@Test
public void testTrimWhitespace() {
    assertEquals(null, trimWhitespace(null));
    assertEquals("", trimWhitespace(""));
    assertEquals("", trimWhitespace(" "));
    assertEquals("", trimWhitespace("\t"));
    assertEquals("a", trimWhitespace(" a"));
    assertEquals("a", trimWhitespace("a "));
    assertEquals("a", trimWhitespace(" a "));
    assertEquals("a b", trimWhitespace(" a b "));
    assertEquals("a b  c", trimWhitespace(" a b  c "));
}

10. trimAllWhitespace(String str)

Trim all whitespace from the given String: leading, trailing, and in between characters.
/**
 * Trim <i>all</i> whitespace from the given {@code String}:
 * leading, trailing, and in between characters.
 * @param str the {@code String} to check
 * @return the trimmed {@code String}
 * @see java.lang.Character#isWhitespace
 */
public static String trimAllWhitespace(String str) {
    if (!hasLength(str)) {
         return str;
    }

    int len = str.length();
    StringBuilder sb = new StringBuilder(str.length());
    for (int i = 0; i < len; i++) {
         char c = str.charAt(i);
         if (!Character.isWhitespace(c)) {
             sb.append(c);
         }
     }
     return sb.toString();
}
JUnit test case:
@Test
public void testTrimAllWhitespace() {
    assertEquals("", trimAllWhitespace(""));
    assertEquals("", trimAllWhitespace(" "));
    assertEquals("", trimAllWhitespace("\t"));
    assertEquals("a", trimAllWhitespace(" a"));
    assertEquals("a", trimAllWhitespace("a "));
    assertEquals("a", trimAllWhitespace(" a "));
    assertEquals("ab", trimAllWhitespace(" a b "));
    assertEquals("abc", trimAllWhitespace(" a b  c "));
}

Alpha, Numeric, and Case Related Methods

11. uppercaseFirstChar(String in)

This method returns the input argument but ensures the first character is capitalized (if possible).
/**
 * Returns the input argument, but ensures the first character is capitalized (if possible).
 * @param in the string to uppercase the first character.
 * @return the input argument, but with the first character capitalized (if possible).
 * @since 1.2
 */
public static String uppercaseFirstChar(String in) {
    if (in == null || in.length() == 0) {
         return in;
    }
    int length = in.length();
    StringBuilder sb = new StringBuilder(length);

    sb.append(Character.toUpperCase(in.charAt(0)));
    if (length > 1) {
         String remaining = in.substring(1);
         sb.append(remaining);
    }
    return sb.toString();
}
JUnit test case:
@Test
public void uppercaseFirstCharTest() {
    assertEquals("Javaguides", uppercaseFirstChar("javaguides"));
    assertEquals("Java", uppercaseFirstChar("java"));
    System.out.println(uppercaseFirstChar("javaguides"));
}

12. isAlphaSpace(CharSequence cs)

This method checks if the CharSequence contains only Unicode letters and space (' ').
public static boolean isAlphaSpace(final CharSequence cs) {
    if (cs == null) {
         return false;
    }
    final int sz = cs.length();
    for (int i = 0; i < sz; i++) {
         if (!Character.isLetter(cs.charAt(i)) && cs.charAt(i) != ' ') {
              return false;
         }
    }
    return true;
}
JUnit test case:
@Test
public void testIsAlphaspace() {
    assertFalse(isAlphaSpace(null));
    assertTrue(isAlphaSpace(""));
    assertTrue(isAlphaSpace(" "));
    assertTrue(isAlphaSpace("a"));
    assertTrue(isAlphaSpace("A"));
    assertTrue(isAlphaSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
    assertTrue(isAlphaSpace("ham kso"));
    assertFalse(isAlphaSpace("1"));
    assertFalse(isAlphaSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
    assertFalse(isAlphaSpace("_"));
    assertFalse(isAlphaSpace("hkHKHik*khbkuh"));
}

13. isAlphanumericSpace(CharSequence cs)

This method checks if the CharSequence contains only Unicode letters, digits, or space (' ').
public static boolean isAlphanumericSpace(final CharSequence cs) {
    if (cs == null) {
         return false;
    }
    final int sz = cs.length();
    for (int i = 0; i < sz; i++) {
         if (!Character.isLetterOrDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
             return false;
         }
    }
    return true;
}
JUnit test case:
@Test
public void testIsAlphanumericSpace() {
    assertFalse(StringUtility.isAlphanumericSpace(null));
    assertTrue(StringUtility.isAlphanumericSpace(""));
    assertTrue(StringUtility.isAlphanumericSpace(" "));
    assertTrue(StringUtility.isAlphanumericSpace("a"));
    assertTrue(StringUtility.isAlphanumericSpace("A"));
    assertTrue(StringUtility.isAlphanumericSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
    assertTrue(StringUtility.isAlphanumericSpace("ham kso"));
    assertTrue(StringUtility.isAlphanumericSpace("1"));
    assertTrue(StringUtility.isAlphanumericSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
    assertFalse(StringUtility.isAlphanumericSpace("_"));
    assertFalse(StringUtility.isAlphanumericSpace("hkHKHik*khbkuh"));
}

14. isNumeric(CharSequence cs)

This method checks if the CharSequence contains only Unicode digits. A decimal point is not a Unicode digit and returns false.
public static boolean isNumeric(final CharSequence cs) {
    if (isEmpty(cs)) {
         return false;
    }
    final int sz = cs.length();
    for (int i = 0; i < sz; i++) {
         if (!Character.isDigit(cs.charAt(i))) {
              return false;
        }
    }
    return true;
}
JUnit test case:
@Test
public void testIsNumeric() {
 assertFalse(StringUtility.isNumeric(null));
 assertFalse(StringUtility.isNumeric(""));
 assertFalse(StringUtility.isNumeric(" "));
 assertFalse(StringUtility.isNumeric("a"));
 assertFalse(StringUtility.isNumeric("A"));
 assertFalse(StringUtility.isNumeric("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
 assertFalse(StringUtility.isNumeric("ham kso"));
 assertTrue(StringUtility.isNumeric("1"));
 assertTrue(StringUtility.isNumeric("1000"));
 assertTrue(StringUtility.isNumeric("\u0967\u0968\u0969"));
 assertFalse(StringUtility.isNumeric("\u0967\u0968 \u0969"));
 assertFalse(StringUtility.isNumeric("2.3"));
 assertFalse(StringUtility.isNumeric("10 00"));
 assertFalse(StringUtility.isNumeric("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
 assertFalse(StringUtility.isNumeric("_"));
 assertFalse(StringUtility.isNumeric("hkHKHik*khbkuh"));
 assertFalse(StringUtility.isNumeric("+123"));
 assertFalse(StringUtility.isNumeric("-123"));
}

15. isNumericSpace(CharSequence cs)

This method checks if the CharSequence contains only Unicode digits or space (' '). A decimal point is not a Unicode digit and returns false.
public static boolean isNumericSpace(final CharSequence cs) {
    if (cs == null) {
          return false;
    }
    final int sz = cs.length();
    for (int i = 0; i < sz; i++) {
         if (!Character.isDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
              return false;
         }
    }
    return true;
}
JUnit test case:
@Test
public void testIsNumericSpace() {
 assertFalse(StringUtility.isNumericSpace(null));
 assertTrue(StringUtility.isNumericSpace(""));
 assertTrue(StringUtility.isNumericSpace(" "));
 assertFalse(StringUtility.isNumericSpace("a"));
 assertFalse(StringUtility.isNumericSpace("A"));
 assertFalse(StringUtility.isNumericSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
 assertFalse(StringUtility.isNumericSpace("ham kso"));
 assertTrue(StringUtility.isNumericSpace("1"));
 assertTrue(StringUtility.isNumericSpace("1000"));
 assertFalse(StringUtility.isNumericSpace("2.3"));
 assertTrue(StringUtility.isNumericSpace("10 00"));
 assertTrue(StringUtility.isNumericSpace("\u0967\u0968\u0969"));
 assertTrue(StringUtility.isNumericSpace("\u0967\u0968 \u0969"));
 assertFalse(StringUtility.isNumericSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
 assertFalse(StringUtility.isNumericSpace("_"));
 assertFalse(StringUtility.isNumericSpace("hkHKHik*khbkuh"));
}

File Related String Utility Methods

16. fromBufferedReader(BufferedReader bufferedReader)

Converts a BufferedReader into a String.
public static String fromBufferedReader(BufferedReader bufferedReader) {
    StringBuffer sb = new StringBuffer();

    try {
         String line = bufferedReader.readLine();

         while (line != null) {
             sb.append(line);
             line = bufferedReader.readLine();
             if (line != null) {
                  sb.append("\n");
             }
         }
     } catch (IOException e) {
          // replace this with log.error
          e.printStackTrace();
     }

     return sb.toString();
}

17. fromInputStream(InputStream inputStream)

Converts an InputStream into a String.
public static String fromInputStream(InputStream inputStream) {
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    return fromBufferedReader(bufferedReader);
}

String Array related Utility Methods

18. arrayToMap(String[][] array)

Converts a 2-dimensional array into a map where the first dimension is 2 cell String array containing key and value respectively. Any array with fewer than 2 elements is ignored.
public static Map<String, String> arrayToMap(String[][] array) {
    Map<String, String> map = new HashMap<String, String>();

    for (String[] pair : array) {
         if (pair.length > 1) {
             // got a pair, add to map
             map.put(pair[0], pair[1]);
         }
    }
    return map;
}

19. startsWith(String[] array, String startsWith)

Searches through a given String array and returns an element that starts with the supplied startsWith string. This method ignores the case. If no match can be found then an empty string is returned.
public static String startsWith(String[] array, String startsWith) {
    String lcStartsWith = startsWith.toLowerCase();
    for (String element : array) {
         if (element.toLowerCase().startsWith(lcStartsWith)) {
             return element;
         }
    }
    return "";
}

Character related Utility Methods

20. trimLeadingCharacter(String str, char leadingCharacter)

This method trims all occurrences of the supplied leading character from the given String.
/**
 * Trim all occurrences of the supplied leading character from the given {@code String}.
 * @param str the {@code String} to check
 * @param leadingCharacter the leading character to be trimmed
 * @return the trimmed {@code String}
 */
public static String trimLeadingCharacter(String str, char leadingCharacter) {
    if (!hasLength(str)) {
        return str;
    }

    StringBuilder sb = new StringBuilder(str);
    while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
        sb.deleteCharAt(0);
    }
     return sb.toString();
}
JUnit test case:
@Test
public void testTrimLeadingCharacter() {
 assertEquals(null, StringUtility.trimLeadingCharacter(null, ' '));
 assertEquals("", StringUtility.trimLeadingCharacter("", ' '));
 assertEquals("", StringUtility.trimLeadingCharacter(" ", ' '));
 assertEquals("\t", StringUtility.trimLeadingCharacter("\t", ' '));
 assertEquals("a", StringUtility.trimLeadingCharacter(" a", ' '));
 assertEquals("a ", StringUtility.trimLeadingCharacter("a ", ' '));
 assertEquals("a ", StringUtility.trimLeadingCharacter(" a ", ' '));
 assertEquals("a b ", StringUtility.trimLeadingCharacter(" a b ", ' '));
 assertEquals("a b  c ", StringUtility.trimLeadingCharacter(" a b  c ", ' '));
}

21. trimTrailingCharacter(String str, char trailingCharacter)

This method trims all occurrences of the supplied trailing character from the given String.
/**
 * Trim all occurrences of the supplied trailing character from the given {@code String}.
 * @param str the {@code String} to check
 * @param trailingCharacter the trailing character to be trimmed
 * @return the trimmed {@code String}
 */
public static String trimTrailingCharacter(String str, char trailingCharacter) {
    if (!hasLength(str)) {
         return str;
    }

    StringBuilder sb = new StringBuilder(str);
    while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {
         sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
}
JUnit test case:
@Test
public void testTrimTrailingCharacter() {
 assertEquals(null, StringUtility.trimTrailingCharacter(null, ' '));
 assertEquals("", StringUtility.trimTrailingCharacter("", ' '));
 assertEquals("", StringUtility.trimTrailingCharacter(" ", ' '));
 assertEquals("\t", StringUtility.trimTrailingCharacter("\t", ' '));
 assertEquals("a", StringUtility.trimTrailingCharacter("a ", ' '));
 assertEquals(" a", StringUtility.trimTrailingCharacter(" a", ' '));
 assertEquals(" a", StringUtility.trimTrailingCharacter(" a ", ' '));
 assertEquals(" a b", StringUtility.trimTrailingCharacter(" a b ", ' '));
 assertEquals(" a b  c", StringUtility.trimTrailingCharacter(" a b  c ", ' '));
}

Other Utility Methods

22. startsWithIgnoreCase( String str, String prefix)

Test if the given string starts with the specified prefix, ignoring upper/lower case.
/**
 * Test if the given {@code String} starts with the specified prefix,
 * ignoring upper/lower case.
 * @param str the {@code String} to check
 * @param prefix the prefix to look for
 * @see java.lang.String#startsWith
 */
public static boolean startsWithIgnoreCase( String str,  String prefix) {
    return (str != null && prefix != null && str.length() >= prefix.length() &&
   str.regionMatches(true, 0, prefix, 0, prefix.length()));
}

23. quote( String str)

Quote the given String with single quotes.
/**
 * Quote the given {@code String} with single quotes.
 * @param str the input {@code String} (e.g. "myString")
 * @return the quoted {@code String} (e.g. "'myString'"),
 * or {@code null} if the input was {@code null}
 */

public static String quote( String str) {
 return (str != null ? "'" + str + "'" : null);
}

24. quoteIfString( Object obj)

Turn the given Object into a String with single quotes if it is a String; keeping the Object as-is else.
/**
 * Turn the given Object into a {@code String} with single quotes
 * if it is a {@code String}; keeping the Object as-is else.
 * @param obj the input Object (e.g. "myString")
 * @return the quoted {@code String} (e.g. "'myString'"),
 * or the input object as-is if not a {@code String}
 */

public static Object quoteIfString( Object obj) {
     return (obj instanceof String ? quote((String) obj) : obj);
}

25. mergeStringArrays(String array1[], String array2[])

/**
 * This String utility or util method can be used to merge 2 arrays of
 * string values. If the input arrays are like this array1 = {"a", "b" ,
 * "c"} array2 = {"c", "d", "e"} Then the output array will have {"a", "b" ,
 * "c", "d", "e"}
 * 
 * This takes care of eliminating duplicates and checks null values.
 * 
 * @param values
 * @return
 */
public static String[] mergeStringArrays(String array1[], String array2[]) {

    if (array1 == null || array1.length == 0)
         return array2;
    if (array2 == null || array2.length == 0)
         return array1;
    List<String> array1List = Arrays.asList(array1);
    List<String> array2List = Arrays.asList(array2);
    List<String> result = new ArrayList<String>(array1List);
    List<String> tmp = new ArrayList<String>(array1List);
    tmp.retainAll(array2List);
    result.removeAll(tmp);
    result.addAll(array2List);
    return ((String[]) result.toArray(new String[result.size()]));
}

public static void main(String[] args) {
    String[] strArray = mergeStringArrays(new String[] {"abc","xyz","pqr"}, new String[] {"ABC","PQR"});
    for(String string : strArray){
         System.out.println(string);
    }
}
Output:
abc
xyz
pqr
ABC
PQR

26. endsWithIgnoreCase(String str, String suffix)

Check a string ends with another string ignoring the case.
/**
* Check a String ends with another string ignoring the case.
*
* @param str
* @param suffix
* @return
*/
public static boolean endsWithIgnoreCase(String str, String suffix) {

    if (str == null || suffix == null) {
        return false;
    }
    if (str.endsWith(suffix)) {
        return true;
    }
    if (str.length() < suffix.length()) {
        return false;
    } else {
        return str.toLowerCase().endsWith(suffix.toLowerCase());
    }
}

27. startsWithIgnoreCase(String str, String prefix)

Check a string starts with another string ignoring the case.
/**
* Check a String starts with another string ignoring the case.
*
* @param str
* @param prefix
* @return
*/

public static boolean startsWithIgnoreCase(String str, String prefix) {

    if (str == null || prefix == null) {
        return false;
    }
    if (str.startsWith(prefix)) {
        return true;
    }
    if (str.length() < prefix.length()) {
        return false;
    } else {
        return str.toLowerCase().startsWith(prefix.toLowerCase());
    }
}
Note that the popular frameworks like Spring, Hibernate, and Apache projects use this kind of common String utility classes or methods as reusable methods.

Check out Apache commons lang3 - Which provides highly reusable static utility methods, chiefly concerned with adding value to the java.lang classes.

Related Posts

References

Comments