Truncating string in java

Truncating string in java

Truncate StringImplement a truncate method for the String class. Check String length before using substring.

Truncate. In Java we often need to ensure a maximum length of Strings. We truncate strings to a length, making Strings that are too long shorter. No built-in method is available.

With substring, we can compose a helpful method to truncate strings. A logical branch, needed to eliminate exceptions, is helpful. This ensures more cases work correctly.

In the tests, the truncate() method works correctly on sizes that are too long (10). It successfully applies substring() to create a 3-char string.

Example code. This program introduces the truncate() method. It receives two parameters—the String to truncate and the length of the desired String.

Detail The if-statement ensures that the substring() method never receives a length that is too long. This avoids errors.

Detail The method does nothing, returning the original string, when the truncate-length is shorter than the String itself.

public class Program < public static String truncate(String value, int length) < // Ensure String length is longer than requested size. if (value.length() > length) < return value.substring(0, length); >else < return value; >> public static void main(String[] args) < String test = «apple»; // . Truncate to 3 characters. String result1 = truncate(test, 3); System.out.println(result1); // . Truncate to larger sizes: no exception occurs. String result2 = truncate(test, 10); System.out.println(result2); String result3 = truncate(test, 5); System.out.println(result3); > >

Читайте также:  Https pb mdsdnr ru privcab index php r user login

Helpful methods, like truncate, are often key to developing more complex programs. Using an abstraction like truncate() makes a more complicated method easier, and clearer, to write.

For performance, truncate() avoids creating strings when possible. It does nothing when no new String is needed. This may help program performance.

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

Источник

What is StringUtils.truncate in Java?

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

Overview

truncate() is a static the methods in Java that can be called without creating an object of the class method of the StringUtils class which is used to truncate a given string. The method accepts:

If the length of the string is less than the specified maximum width, then the method returns the input string. Otherwise, the method returns the substring i.e substring(str, 0, maxWidth) .

If the maximum width is less than zero, then an IllegalArgumentException is thrown.

How to import StringUtils

The definition of StringUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:

 org.apache.commons commons-lang3 3.12.0  

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the StringUtils class as follows:

import org.apache.commons.lang3.StringUtils; 

Syntax

public static String truncate(final String str, final int maxWidth) 

Parameters

  • final String str : The string to truncate.
  • final int maxWidth : The maximum length of the result string.

Return value

This method returns the truncated string.

Code

import org.apache.commons.lang3.StringUtils;
public class Main
public static void main(String[] args)
String s = "hellO-EDUcative";
int maxWidth = 5;
System.out.printf("The output of StringUtils.truncate() for the string - '%s' is %s", s, StringUtils.truncate(s, maxWidth));
System.out.println();
maxWidth = 20;
System.out.printf("The output of StringUtils.truncate() for the string - '%s' is %s", s, StringUtils.truncate(s, maxWidth));
System.out.println();
s = "";
System.out.printf("The output of StringUtils.truncate() for the string - '%s' is %s", s, StringUtils.truncate(s, maxWidth));
System.out.println();
s = null;
System.out.printf("The output of StringUtils.truncate() for the string - '%s' is %s", s, StringUtils.truncate(s, maxWidth));
System.out.println();
maxWidth = -1;
System.out.printf("The output of StringUtils.truncate() for the string - '%s' is %s", s, StringUtils.truncate(s, maxWidth));
System.out.println();
>
>

Example 1

The method returns hellO , i.e., the substring from index zero to four.

Example 2

The method returns hellO-EDUcative , i.e., the whole input string, because the maximum width is greater than the length of the string.

Example 3

The method returns «» as the input string is empty.

Example 4

The method returns null as the input string is null .

Example 5

The method throws an IllegalArgumentException as the specified width is less than zero.

Output

The output of the code will be as follows:

The output of StringUtils.truncate() for the string - 'hellO-EDUcative' is hellO The output of StringUtils.truncate() for the string - 'hellO-EDUcative' is hellO-EDUcative The output of StringUtils.truncate() for the string - '' is The output of StringUtils.truncate() for the string - 'null' is null Exception in thread "main" java.lang.IllegalArgumentException: maxWith cannot be negative at org.apache.commons.lang3.StringUtils.truncate(StringUtils.java:9263) at org.apache.commons.lang3.StringUtils.truncate(StringUtils.java:9195) at Main.main(Main.java:24) 

Источник

Truncating string in java

In this tutorial, we will learn various ways to String truncate to the desired number of characters in Java.

We’ll start by exploring ways to do this using the JDK itself. Then we’ll look at how to do this using some popular third-party libraries.

2. Use JDK truncation String

Java provides many convenient methods for truncation String . let’s see.

2.1. Use ** String’ the substring() ** method

String The class comes with a convenience method called as the substring. name suggests that , substring() returns the part given String between the specified indices .

static String usingSubstringMethod(String text, int length) if (text.length() <= length) return text; 
> else return text.substring(0, length);
>
>

In the above example, if the specified length is length greater than text , we return text itself. This is due to the number of characters passed to greater than substring() length String IndexOutOfBoundsException in .

Otherwise, we return starting at index 0 and extending to (but not including) index length.

Let’s confirm this with a test case:

static final String TEXT = "Welcome to baeldung.com"; 
@Test
public void givenStringAndLength_whenUsingSubstringMethod_thenTrim() assertEquals(TrimStringOnLength.usingSubstringMethod(TEXT, 10), "Welcome to");
>

As we can see , the start index is inclusive and the end index is exclusive . Therefore, the character at the index length will not be included in the returned substring.

2.2. String’ The split() method used

Another way to truncate String is to use a split() method, which uses regular expressions to String split into pieces.

Here we will use a regular expression feature called positive lookbehind to match String a specified number of characters starting from the beginning:

static String usingSplitMethod(String text, int length) String[] results = text.split("(?)"); 
return results[0];
>

results The first element of will be our truncated , or original String if length greater than . text String

@Test 
public void givenStringAndLength_whenUsingSplitMethod_thenTrim() assertEquals(TrimStringOnLength.usingSplitMethod(TEXT, 13), "Welcome to ba");
>

2.3. Using Pattern classes

Similarly, we can use the Pattern class to compile a regular expression that matches String the beginning up to a specified number of characters .

For example, let’s use . this regular expression to match at least one and at most length characters:

static String usingPattern(String text, int length) Optional result = Pattern.compile(".") 
.matcher(text)
.results()
.map(MatchResult::group)
.findFirst();
return result.isPresent() ? result.get() : EMPTY;
>

As we saw above, after compiling our regex into Pattern , we can use Pattern’s matcher() methods to interpret our regex in terms of that String . Then we can group the results and return the first one, which is what we truncated String .

Now let’s add a test case to verify that our code is working as expected:

@Test 
public void givenStringAndLength_whenUsingPattern_thenTrim() assertEquals(TrimStringOnLength.usingPattern(TEXT, 19), "Welcome to baeldung");
>

2.4. Using the CharSequence’ sc odePoints() method

Java 9 provides a codePoints() method to String convert to a stream of code point values .

Let’s see how to use this method in combination with the streaming API to truncate a string:

static String usingCodePointsMethod(String text, int length) return text.codePoints() 
.limit(length)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
>

Here, we use the limit() method will be Stream limited to the given length . Then we use StringBuilder to build our truncated string.

Next, let’s verify that our approach works:

@Test 
public void givenStringAndLength_whenUsingCodePointsMethod_thenTrim() assertEquals(TrimStringOnLength.usingCodePointsMethod(TEXT, 6), "Welcom");
>

3. Apache Commons Libraries

The Apache Commons Lang library contains a class for String manipulation StringUtils .

First, let’s add the Apache Commons dependency to ours pom.xml :

 
org.apache.commons
commons-lang3
3.12.0

3.1. StringUtils’s left() How to use

StringUtils There is a useful static method called left() . Return the leftmost specified number of characters StringUtils.left() in a null-safe manner : String

static String usingLeftMethod(String text, int length) return StringUtils.left(text, length); 
>

3.2. StringUtils’ Methods truncate() used

Alternatively, we can use StringUtils.truncate() to achieve the same goal:

public static String usingTruncateMethod(String text, int length) return StringUtils.truncate(text, length); 
>

4. Guava library

In addition to using core Java methods and Apache Commons libraries for truncation String , we can also use Guava. Let’s start by adding the Guava dependency to our pom.xml file:

 
com.google.guava
guava
31.0.1-jre

Now we can use Guava’s Splitter classes to truncate our String :

static String usingSplitter(String text, int length) Iterable parts = Splitter.fixedLength(length) 
.split(text);
return parts.iterator()
.next();
>

We use split Splitter.fixedLength() ours String into given length multiple parts. Then, we return the first element of the result.

5 Conclusion

In this article, we learned various ways to String truncate to a specific number of characters in Java.

We looked at some ways to do this with the JDK. Then we truncated using several 3rd party libraries String .

Источник

Оцените статью