Core Java

Retrieving First n Characters in a String in Java

When working with strings in Java, there are different ways to extract the first n characters efficiently. This article will explore achieving this using standard JDK methods and then showcase alternative approaches using external libraries such as Apache Commons Lang and Guava.

1. Using JDK Methods and Classes

Java provides various built-in methods to manipulate strings.

1.1 Using the substring() Method

To extract the first n characters from a string, we can use the substring method of the String class:

public class GetFirstNCharacters {

    public static String getFirstNCharacters(String input, int n) {

        return input.substring(0, n);

    }

    public static void main(String[] args) {

        String originalString = "Alice in Wonderland";
        int n = 5; // Number of characters to extract

        String firstNCharacters = getFirstNCharacters(originalString, n);
        System.out.println("First " + n + " characters: " + firstNCharacters);
    }

}

In this example:

  • The getFirstNCharacters method takes an input string input and an integer n specifying the number of characters to extract.
  • We use input.substring(0, n) on the str object. The first argument 0 indicates the starting index (inclusive). The second argument, n specifies the ending index (exclusive).

Important Note: If n is greater than the length of the String, substring() throws a StringIndexOutOfBoundsException. It is essential to handle this potential exception in our code, especially when dealing with user-provided input or String lengths that might vary. Here is an example:

public class GetFirstNCharacters {

    public static String getFirstNCharacters(String input, int n) {
        
        if (input == null || input.isEmpty() || n <= 0) {
            return "";
        }
        return input.substring(0, Math.min(n, input.length()));
    }

    public static void main(String[] args) {
        
        String originalString = "Alice in Wonderland";
        int n = 5; // Number of characters to extract

        String firstNCharacters = getFirstNCharacters(originalString, n);
        System.out.println("First " + n + " characters: " + firstNCharacters);
    }  
}

The above example uses input.substring(0, Math.min(n, input.length())) to get the substring from the beginning (index 0) up to the minimum of n and the length of the input string, ensuring we don’t exceed the string length.

The output is:

Fig 1: Example output using the substring() method in Java to get the first n characters
Fig 1: Example output using the substring() method in Java to get the first n characters

1.2 Using subSequence Method

The subSequence method in Java provides an alternative way to obtain a portion of a string as a CharSequence. This method also takes two arguments: the starting index (inclusive) and the ending index (exclusive) of the desired substring.

public class GetFirstNCharacters {

    public static String getFirstNCharacters(String input, int n) {
        if (input == null || input.isEmpty() || n <= 0) {
            return "";
        }
        return input.subSequence(0, Math.min(n, input.length())).toString();
    }
    
    public static void main(String[] args) {
        
        String originalString = "The Three Musketeers";
        int n = 3; // Number of characters to extract

        String firstNCharacters = getFirstNCharacters(originalString, n);
        System.out.println("First " + n + " characters: " + firstNCharacters);
    }  
}

Output is:

First 3 characters: The

1.3 Using chars Method

The chars() method in Java 8+ returns an IntStream of Unicode code points representing the characters in the string. By limiting the stream with limit(n), we extract the first n characters efficiently. The collected code points are then concatenated into a String using a StringBuilder, providing an efficient method to get the initial characters.

public class GetFirstNCharacters {
    
    public static String getFirstNCharacters(String input, int n) {
        if (input == null || input.isEmpty() || n <= 0) {
            return "";
        }
        return input.chars().limit(n).collect(StringBuilder::new,
                                              StringBuilder::appendCodePoint,
                                              StringBuilder::append)
                         .toString();
    }
    
    public static void main(String[] args) {
        
        String originalString = "Alice in Wonderland";
        int n = 5; // Number of characters to extract

        String firstNCharacters = getFirstNCharacters(originalString, n);
        System.out.println("First " + n + " characters: " + firstNCharacters);
    }  
}

Output is:

First 5 characters: Alice

2. Using External Libraries

Now let us see how to achieve the same outcome using external libraries such as Apache Commons Lang and Guava.

2.1 Apache Commons Lang

The Apache Commons Lang library provides a utility class, StringUtils, which provides methods for common String manipulation tasks. The substring() method in StringUtils has a null-safety advantage over the core JDK implementation. It returns an empty String instead of throwing an exception if the input String is null. Here’s how to use StringUtils.substring() to get the first n characters:

Dependency (Maven pom.xml):

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

Code Example:

import org.apache.commons.lang3.StringUtils;

public class GetFirstNCharsApacheLang {

     public static void main(String[] args) {
        String originalString = "Hello, world!";
        int n = 5; // Number of characters to extract

        String firstNCharacters = StringUtils.substring(originalString, 0, n);
        System.out.println("First " + n + " characters: " + firstNCharacters);
    }
}

To achieve the same result using this library, we can update the above code snippet and use the StringUtils.left method.

String firstNCharacters = StringUtils.left(originalString, n);

In this example, the StringUtils.left method is used to get the leftmost n characters of the input string originalString.

The output is:

First 5 characters: Hello

2.2 Using Guava

To achieve the task of extracting the first n characters from a string using Guava, we can utilize the Ascii.truncate method, which is part of the Guava library. This method efficiently truncates a string to a specified maximum length while handling Unicode characters correctly.

Dependency (Maven):

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

Code Example:

import com.google.common.base.Ascii;

public class GetFirstNCharactersGuava {

    public static void main(String[] args) {
        
        String originalString = "Alice in Wonderland";
        int n = 5; // Number of characters to extract

        String firstNCharacters = Ascii.truncate(originalString, n, "");
        System.out.println("First " + n + " characters: " + firstNCharacters);
    }
}

In this example:

  • We import Ascii from com.google.common.base.
  • The Ascii.truncate method is used to truncate originalString to the first n characters. The third argument ("") specifies the string to append if truncation occurs. In this case, passing an empty string "" indicates that no additional characters should be appended after truncation.

Output is:

First 5 characters: Alice

3. Conclusion

In this article, we have explored various methods In Java for extracting the first n characters from a string. This can be efficiently done using JDK methods like substring, subSequence, and chars, or by leveraging external libraries such as Apache Commons Lang and Guava. Depending on our project requirements and existing dependencies, we can choose the approach that best suits our needs. Each method provides flexibility and ease of use for string manipulation tasks.

4. Download the Source Code

This article was about retrieving the first n characters in a String in Java.

Download
You can download the full source code of this example here: Retrieving First n Characters in a String in Java

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button