How do I align string print out in left, right, center alignment?

The following code snippet will teach you how to align string in left, right or center alignment when you want to print out string to a console. We will print the string using the printf(String format, Object... args) method. The format specifier / parameter defines how the string will be formatted for output and the args is the value that will be formatted.

The format parameter / specifier include flags, width, precision and conversion-characters in the order shown below. The square brackets in the notation means the part is an optional parameter.

% [flags] [width] [.precision] conversion-character
Flags Description
- left-align the output, when not specified the default is to right-align
+ print (+) or (-) sign for numeric value
0 zero padded a numeric value
, comma grouping separator for number greater that 1000
space will output a (-) symbol for negative value and a space if positive
Conversion Description
s string, use capital S to uppercase the strings
c character, use capital C to uppercase the characters
d integer: byte, short, integer, long
f floating point number: float, double
n new line

Width: Defines the field width for printing out the value of argument. It also represents the minimum number of characters to
be printed out to the output.

Precision: For floating-point conversion the precision define the number of digits of precision in a floating point value. For string value this will extract the substring.

To center the string for output we use the StringUtils.center() method from the Apache Commons Lang library. This method will center-align the string str in a larger string of size using the default space character (‘ ‘). You can supply the third parameter to define your own space character / string.

package org.kodejava.example.lang;

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class StringAlignment {
    private static Object[][] people = {
        {"Alice", LocalDate.of(2000, Month.JANUARY, 1)},
        {"Bob", LocalDate.of(1989, Month.DECEMBER, 15)},
        {"Carol", LocalDate.of(1992, Month.JULY, 24)},
        {"Ted", LocalDate.of(2006, Month.MARCH, 13)},
    };

    public static void main(String[] args) {
        String nameFormat = "| %1$-20s | ";
        String dateFormat = " %2$tb %2$td, %2$tY  | ";
        String ageFormat = " %3$3s |%n";
        String format = nameFormat.concat(dateFormat).concat(ageFormat);
        String line = new String(new char[48]).replace('\0', '-');

        System.out.println(line);
        System.out.printf("|%s|%s|%s|%n",
            StringUtils.center("Name", 22),
            StringUtils.center("Birth Date", 16),
            StringUtils.center("Age", 6));
        System.out.println(line);

        for (Object[] data : people) {
            System.out.printf(format,
                data[0], data[1],
                ChronoUnit.YEARS.between((LocalDate) data[1], LocalDate.now()));
        }

        System.out.println(line);
    }
}

Here is the output of our code snippet above:

------------------------------------------------
|         Name         |   Birth Date   | Age  |
------------------------------------------------
| Alice                |  Jan 01, 2000  |   17 |
| Bob                  |  Dec 15, 1989  |   27 |
| Carol                |  Jul 24, 1992  |   24 |
| Ted                  |  Mar 13, 2006  |   10 |
------------------------------------------------

Maven Dependencies

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.5</version>
</dependency>

How do I find text between two strings?

In this example we’ll use the StringUtils.substringBetween() method. Here we’ll extract the title and body of our HTML document. Let’s see the code.

package org.kodejava.example.commons.lang;

import java.util.Date;
import org.apache.commons.lang.StringUtils;

public class NestedString {
    public static void main(String[] args) {
        String helloHtml = "<html>" +
                "<head>" +
                "   <title>Hello World from Java</title>" +
                "<body>" +
                "Hello, today is: " + new Date() +
                "</body>" +
                "</html>";

        String title = StringUtils.substringBetween(helloHtml, "<title>", "</title>");
        String content = StringUtils.substringBetween(helloHtml, "<body>", "</body>");

        System.out.println("title = " + title);
        System.out.println("content = " + content);
    }
}

By print out the title and content we’ll see something similar to:

title = Hello World from Java
content = Hello, today is: Tue Apr 08 07:02:39 ICT 2008

How do I count word occurrences in a string?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class WordCountExample {
    public static void main(String[] args) {
        // We have the source text we'll do the search on.
        String source = "From the download page, you can download the Java " +
                "Tutorials for browsing offline. Or you can just download " +
                "the examples.";
        // The word we want to count its occurrences
        String word = "you";

        // Using StringUtils.countMatches() method we can count the occurrences
        // frequency of a word/letter in the giver source of string.
        int wordFound = StringUtils.countMatches(source, word);

        // Print how many we have found the word
        System.out.println(wordFound + " occurrences of the word '" + word +
                "' was found in the text.");
    }
}

Here is the result of the code above.

2 occurrences of the word 'you' was found in the text.

How do I reverse a string, words or sentences?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class StringReverseExample {    
    public static void main(String[] args) {
        // We have an original string here that we'll need to reverse.
        String words = "The quick brown fox jumps over the lazy dog";

        // Using StringUtils.reverse we can reverse the string letter by letter.
        String reversed = StringUtils.reverse(words);

        // Now we want to reverse per word, we can use 
        // StringUtils.reverseDelimited() method to do this.
        String delimitedReverse = StringUtils.reverseDelimited(words, ' ');

        // Print out the result
        System.out.println("Original: " + words);
        System.out.println("Reversed: " + reversed);
        System.out.println("Delimited Reverse: " + delimitedReverse);
    }
}

Here is the result:

Original: The quick brown fox jumps over the lazy dog
Reversed: god yzal eht revo spmuj xof nworb kciuq ehT
Delimited Reverse: dog lazy the over jumps fox brown quick The

How do I check if a string is empty or not?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class EmptyStringCheckExample {
    public static void main(String[] args) {
        // Create some variable to hold some string that empty, contains only
        // white spaces and words.
        String one = "";
        String two = "\t\r\n";
        String three = "     ";
        String four = null;
        String five = "four four two";

        // We can use StringUtils class for checking if a string is empty or not
        // using StringUtils.isBlank() method. This method will return true if
        // the tested string is empty, contains white space only or null.
        System.out.println("Is one empty? " + StringUtils.isBlank(one));
        System.out.println("Is two empty? " + StringUtils.isBlank(two));
        System.out.println("Is three empty? " + StringUtils.isBlank(three));
        System.out.println("Is four empty? " + StringUtils.isBlank(four));
        System.out.println("Is five empty? " + StringUtils.isBlank(five));

        // On the other side, the StringUtils.isNotBlank() methods complement
        // the previous method. It will check is a tested string is not empty.
        System.out.println("Is one not empty? " + StringUtils.isNotBlank(one));
        System.out.println("Is two not empty? " + StringUtils.isNotBlank(two));
        System.out.println("Is three not empty? " + StringUtils.isNotBlank(three));
        System.out.println("Is four not empty? " + StringUtils.isNotBlank(four));
        System.out.println("Is five not empty? " + StringUtils.isNotBlank(five));
    }
}

Here is the result:

Is one empty? true
Is two empty? true
Is three empty? true
Is four empty? true
Is five empty? false

Is one not empty? false
Is two not empty? false
Is three not empty? false
Is four not empty? false
Is five not empty? true