How do I remove leading and trailing white space from string?

package org.kodejava.example.lang;

public class TrimStringExample {
    public static void main(String[] args) {
        String text = "     tattarrattat     ";
        System.out.println("Original      = " + text);
        System.out.println("text.length() = " + text.length());

        // The trim() method will result a new string object with a leading and
        // trailing while space removed.
        text = text.trim();
        System.out.println("Result        = " + text);
        System.out.println("text.length() = " + text.length());
    }
}

The result of the code snippet above:

Original      =      tattarrattat     
text.length() = 22
Result        = tattarrattat
text.length() = 12

How do I convert string to char array?

Here we have a small class that convert a string literal into array, a character array. To do this we can simply used String.toCharArray() method.

package org.kodejava.example.lang;

public class StringToArrayExample {
    public static void main(String[] args) {
        // We have a string literal that contains the motto of this website.
        String literal = "Kode Java - Learn Java Programming by Examples";

        // Now we want to convert or divided it into a small array of char.
        // To do this we can simply used String.toCharArray() method. This
        // method splits the string into an array of characters.
        char[] temp = literal.toCharArray();

        // Here we just iterate the char array and print it to our console.
        for (int i = 0; i < temp.length; i++) {
            System.out.print(temp[i]);
        }
    }
}

How do I check a string starts with a specific word?

To test if a string starts with a specific word we can use the String.startsWith() method. This method returns a boolean true as the result if the string starts with that specific word.

package org.kodejava.example.lang;

public class StringStartsWithExample {
    public static void main(String[] args) {
        String str = "The quick brown fox jumps over the lazy dog";

        // See if the fox is a quick fox.
        if (str.startsWith("The quick")) {
            System.out.println("Yes, the fox is the quick one");
        } else {
            System.out.println("The fox is a slow fox");
        }
    }
}

The code snippet print the following output:

Yes, the fox is the quick one