Java Truncate ASCII String using Google Guava

Tags: Google Guava Ascii String Truncate

In this Java tutorial we learn how to use the com.google.common.base.Ascii class of Google Guava library to truncate an ASCII String with a given max length and truncation indicator.

How to add Google Guava library to the Java project

To use the Google Guava library in the Gradle build project, add the following dependency into the build.gradle file.

implementation group: 'com.google.guava', name: 'guava', version: '30.1.1-jre'

To use the Google Guava library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version>
</dependency>

To have more information about the Google Guava library you can visit the project home page at guava.dev

How to truncate a String in Java

In the following Java example program, we show you how to use the Ascii.truncate() method to truncate a given ASCII String with specific max length and truncation indicator String.

AsciiTruncateExample.java

import com.google.common.base.Ascii;

public class AsciiTruncateExample {
    public static void main(String... args) {
        String result1 = Ascii.truncate("Simple Solution", 9, "...");
        String result2 = Ascii.truncate("Simple Solution", 100, "...");

        System.out.println(result1);
        System.out.println(result2);
    }
}
The output is:
Simple...
Simple Solution

Happy Coding 😊