Java string delete last char

Remove Last Character from String in Java

In this tutorial, we are going to shed light on how to remove the last character from a string in Java.

First, we will start by exploring different ways to do so in Java 7. Then, we are going to showcase how to accomplish the same objective using Java 8 or above methods.

Finally, we will explain how to use external libraries such as Apache Commons.

Remove the Last Character in Java 7

JDK 7 offers multiple methods and classes that we can use to remove a character from a string. Let’s take a close look at each option.

Using substring() Method

Typically, substring() provides the easiest and fastest way to delete the last char in Java.

As the name implies, this method returns a portion that is a substring of the given string. As a matter of fact, substring() accepts two parameters that denote the first index and the last one.

So, all we need to do to remove the last character is to pass 0 as the starting index and the length()-1 as the ending index.

Читайте также:  Python прогресс бар загрузки файла

Now, let’s see it in action:

 public static String usingSubstringMethod(String text) < if (text == null || text.length() == 0) < return text; > return text.substring(0, text.length() - 1); > 

As we can see, the method is not null-safe, this is why we added the null-check control and the length condition.

Using replaceAll() with Regex

Alternatively, we can rely on regular expressions to delete the last character from a string.

All we need to do is find the right regex and use the replaceAll() method to match the string against it.

For example, in our case we can use ”.$” which matches the last char of a given string:

 public static String usingRegex(String text) < if (text == null || text.length() == 0) < return text; > return text.replaceAll(".$", ""); > 

Using StringBuffer.deleteCharAt() Method

Another solution would be using the StringBuffer class.

This class simply denotes a mutable sequence of characters. Unlike the String class, StringBuffer is thread-safe and modifiable.

Among the methods of this class, we find deleteCharAt(int index) that can be used to delete the char at the specified index.

Let’s see how we can use it to delete the character at the end of a particular string:

 public static String usingStringBufferClass(String text) < if (text == null || text.length() == 0) < return text; > StringBuffer strBuffer = new StringBuffer(text); return strBuffer.deleteCharAt(text.length() - 1) .toString(); > 

The position that holds the last character is text.length()-1. We used the toString() method to get the string from our StringBuffer object.

Please bear in mind that deleteCharAt(int index) throws StringIndexOutOfBoundsException if the specified index is negative or greater than the length of the string.

Using StringBuilder Class

Similarly, we can use StringBuilder to achieve the same purpose. The difference between StringBuffer and StringBuilder is that StringBuilder is not thread-safe.

StringBuilder offers also the deleteCharAt() method. However, we will use here another method called delete() to remove the last char.

Let’s illustrate the use of the StringBuilder.delete() method using a practical example:

 public static String usingStringBuilderClass(String text) < if (text == null || text.length() == 0) < return text; > StringBuffer strBuffer = new StringBuffer(text); return strBuffer.delete(text.length() - 1, text.length()) .toString(); > 

As shown above, the delete() method removes the characters between the passed indexes. In our case, the removed char will be simply the last one.

Delete the last Char in Java 8 and Above

Now, that we know how to delete the last char using Java 7, let’s see how we can do the same thing using Java 8.

Using Optional Class

As we can see in the previous examples, the first thing we need to deal with before implementing the removal logic is making sure that our string is not null and not empty.

Well, the good news is that we don’t have to do this with the Optional Class. This class provides a concise and efficient way to handle the null-check.

So, without further ado, let’s see it in action:

 public static String usingOptionalClass(String text) < return Optional.ofNullable(text) .filter(str -> str.length() != 0) .map(str -> str.substring(0, str.length() - 1)) .orElse(text); > 

Obviously, Optional offers a fancy way to remove the last char of a particular string in a null-safe manner.

Using Java 9 codePoints() Method

Java 9 upgrades the String class with a brand new handy method called codePoints().

Simply put, this method returns a stream of code point values from a string.

Now, let’s demonstrate the use of this new method with an example:

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

As we can see, we used the limit(text.length()-1) method to tell the stream to ignore and delete the last character.

Apache Commons Lang3 Library

The Apache Commons Lang library provides the StringUtils class for string manipulation.

First, we need to add the Apache Commons dependency to our pom.xml.

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

StringUtils comes with two handy methods that we can use to delete the character at the end of a string.

So, let’s dig deep and explore each one.

Using StringUtils.chop() Method

StringUtils provides the chop() method, especially to remove the last character from a string.

This method accepts a String object as a parameter. The good thing about chop() is that it’s null-safe, so we don’t have to worry about null or empty strings.

 public static String usingStringUtilsChopMethod(String text) < return StringUtils.chop(text); > 

Using StringUtils.substring() Method

StringUtils.substring() returns a substring from a given string in an exception-safe manner. Its internal implementation handles the null-check.

The method requires three parameters: the string, the first, and the last index:

 public static String usingStringUtilsSubstringMethod(String text) < int lastIndex = text != null ? text.length() - 1 : 0; return StringUtils.substring(text, 0, lastIndex); > 

Conclusion

In summary, we have covered in-depth different ways to remove the last character from a string in Java.

We explored a couple of ways to achieve this using built-in Java 7 and Java8 methods. Along the way, we showcased how to accomplish the same thing using the Apache Commons Lang library.

Liked the Article? Share it on Social media!

If you enjoy reading my articles, buy me a coffee ☕. I would be very grateful if you could consider my request ✌️

Источник

Java string delete last char

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Remove the last character of a string in Java

In this quick article, we’ll look at different ways to remove the last character of a string in Java.

The easiest and quickest way to remove the last character from a string is by using the String.substring() method. Here is an example:

String str = "Hey, there!!"; // remove last character (!) str = str.substring(0, str.length() -1); // print the new string System.out.println(str); 

As you can see above, we are using substring() with two parameters. The first parameter is the starting inclusive index which is 0 in our case. The second parameter is basically the ending exclusive index, calculated by taking the length of the string using the length() method and by subtracting 1 from the length. Now if you execute the code, you should see the following output:

However, there is a minor issue. The substring() method is not null-safe, which means it will through an exception if the string is null or empty. To avoid the exception, we have to explicitly check the length of the string as shown in the below example:

str = Optional.ofNullable(str) .filter(s -> !s.isEmpty()) .map(s -> s.substring(0, s.length() - 1)) .orElse(str); 

Another way to remove the last character from a string is by using a regular expression with the replaceAll() method. This method replaces all occurrences of the matched string with the given string. The replaceAll() method takes two input parameters: the regular expression and the replacement string. Here is an example code snippet that removes the last character of the string using replaceAll() :

String str = "Hello World!"; // remove last character (!) str = str.replaceAll(".$", ""); // print the new string System.out.println(str); 

Since replaceAll() is a part of the String class, it is not null-safe. So we have to do a little more work:

The replaceAll() method compiles the regular expression every time it executes. To avoid this unnecessary compilation, you should use the Pattern class to compile the regular expression into a patternjava:

Pattern pattern = Pattern.compile(".$"); str = str != null && !str.isEmpty() ? pattern.matcher(str).replaceAll("") : null; 

The equivalent example that uses Java 8 streams to remove the last character of the string:

str = Optional.ofNullable(str) .map(s -> s.replaceAll(".$", "")) .orElse(str); 

The Apache Commons Lang library is a popular open-source library that provides many utility classes. One such class is the StringUtils that offers useful utility methods for string operations. To add the library to your Maven project, add the following dependency to pom.xml file:

dependency> groupId>org.apache.commonsgroupId> artifactId>commons-lang3artifactId> version>3.9version> dependency> 
implementation 'org.apache.commons:commons-lang3:3.9' 

To remove the class character from a string, just use the StringUtils.substring() method. This method is null-safe, which means it won’t throw an exception if the string is null :

String str = "Hello World!"; // remove last character (!) StringUtils.substring(str, 0, str.length() - 1); // print the new string System.out.println(str); 

The StringUtils.substring() method takes one extra parameter than the built-in substring() ; the string you want to remove a character from. Read Next: How to extract digits from a string in Java ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

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