Remove Whitespace in String and Case insensitive switch


Remove Whitespace from the Beginning and End of a String


The trim() method returns a new String with the leading and trailing whitespace removed.

String str = new String(" Tutor Joes! ");
String t = str.trim(); // t = "Tutor Joes!"

If you trim a String that doesn't have any whitespace to remove, you will be returned the same String instance.

Note that the trim() method has its own notion of whitespace, which differs from the notion used by the Character.isWhitespace() method:

  • All ASCII control characters with codes U+0000 to U+0020 are considered whitespace and are removed by trim(). This includes U+0020 'SPACE', U+0009 'CHARACTER TABULATION', U+000A 'LINE FEED' and U+000D 'CARRIAGE RETURN' characters, but also the characters like U+0007 'BELL'.
  • Unicode whitespace like U+00A0 'NO-BREAK SPACE' or U+2003 'EM SPACE' are not recognized by trim().

Case insensitive switch


switch itself can not be parameterised to be case insensitive, but if absolutely required, can behave insensitive to the input string by using toLowerCase() or toUpperCase:

String inputString = "VALUE";
 
switch (inputString.toLowerCase())
{
    case "value1":
        // ...
        break;
    case "value2":
        // ...
        break;
}
 

Beware

  • Locale might affect how changing cases happen!
  • Care must be taken not to have any uppercase characters in the labels - those will never get executed!

Getting the length of a String


In order to get the length of a String object, call the length() method on it. The length is equal to the number of UTF-16 code units (chars) in the string.

String myString = "Another string example";
System.out.println(myString.length()); // prints out the length of the string

A char in a String is UTF-16 value. Unicode codepoints whose values are ≥ 0x1000 (for example, most emojis) use two char positions. To count the number of Unicode codepoints in a String, regardless of whether each codepoint fits in a UTF-16 char value, you can use the codePointCount method:

int length = str.codePointCount(0, str.length());

You can also use a Stream of codepoints, as of Java 8:

int length = str.codePoints().count();

Basic Programs