Java delete last character

Java remove last character from string

In this post, we will see how to remove last character from String in java.

There are many ways to do it. Let’s see each one by one.

Using String.substring()

We can use inbuilt String’s substring() method to remove last character.We need two parameters here
start index: 0
end index:str.length()-1

Please note that this method is not thread safe and it will fail with empty or null String.
So here is java program to remove last character from String in java.

Using StringUtils.chop()

You need to add below dependency to get Apache commons lang jar.

and then use StringUtils.chop() method to remove last character from the String in java,

Using Regular Expression

We can make use of Regular expression also to remove last character from String in java.

Читайте также:  Open file in new window javascript

Using StringBuffer/StringBuilder

We can StringBuffer’s deleteCharAt() to remove last character from String in java.

That’s all about how to remove last character from String in java.

Was this post helpful?

Share this

Author

Convert UUID to String in Java

Table of ContentsIntroductionUUID class in JavaConvert UUID to String in Java Introduction In this article, we will have a look on How to Convert UUID to String in Java. We will also shed some light on the concept of UUID, its use, and its corresponding representation in Java class. Let us have a quick look […]

Repeat String N times in Java

Table of ContentsIntroductionWhat is a String in Java?Repeat String N times in JavaSimple For Loop to Repeat String N Times in JavaUsing Recursion to Repeat String N Times in JavaString.format() method to Repeat String N Times in JavaUsing String.repeat() method in Java 11 to Repeat String N TimesRegular Expression – Regex to Repeat String N […]

How to Replace Space with Underscore in Java

Table of ContentsReplace space with underscore in java1. Using replace() method2. Using replaceAll() method Learn about how to replace space with underscore in java. Replace space with underscore in java 1. Using replace() method Use String’s replace() method to replace space with underscore in java. String’s replace() method returns a string replacing all the CharSequence […]

How to Replace Comma with Space in Java

Table of ContentsReplace comma with space in java1. Using replace() method2. Using replaceAll() method Learn about how to replace comma with space in java. Replace comma with space in java 1. Using replace() method Use String’s replace() method to replace comma with space in java. Here is syntax of replace() method: [crayon-64be11cf77193655056075/] [crayon-64be11cf77199385812138/] Output: 1 […]

Remove Parentheses From String in Java

Table of ContentsJava StringsRemove Parentheses From a String Using the replaceAll() MethodRemove Parentheses From a String by TraversingConclusion Java uses the Strings data structure to store the text data. This article discusses methods to remove parentheses from a String in Java. Java Strings Java Strings is a class that stores the text data at contiguous […]

Escape percent sign in java

Escape percent sign in String’s format method in java

Table of ContentsEscape Percent Sign in String’s Format Method in JavaEscape Percent Sign in printf() Method in Java In this post, we will see how to escape Percent sign in String’s format() method in java. Escape Percent Sign in String’s Format Method in Java String’s format() method uses percent sign(%) as prefix of format specifier. […]

Источник

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.

Источник

How To Remove a Character from a String in Java

How To Remove a Character from a String in Java

In this article, you’ll learn a few different ways to remove a character from a String object in Java. Although the String class doesn’t have a remove() method, you can use variations of the replace() method and the substring() method to remove characters from strings.

Note: String objects are immutable, which means that they can’t be changed after they’re created. All of the String class methods described in this article return a new String object and do not change the original object. The type of string you use depends on the requirements of your program. Learn more about other types of string classes and why strings are immutable in Java.

The String class has the following methods that you can use to replace or remove characters:

  • replace(char oldChar, char newChar) : Returns a new String object that replaces all of the occurrences of oldChar in the given string with newChar . You can also use the replace() method, in the format replace(CharSequence target, CharSequence replacement) , to return a new String object that replaces a substring in the given string.
  • replaceFirst(String regex, String replacement) : Returns a new String object that replaces the first substring that matches the regular expression in the given string with the replacement.
  • replaceAll(String regex, String replacement) : Returns a new String object that replaces each substring that matches the regular expression in the given string with the replacement.
  • substring(int start, int end) : Returns a new String object that contains a subsequence of characters currently contained in this sequence. The substring begins at the specified start and extends to the character at index end minus 1.

Notice that the first argument for the replaceAll() and replaceFirst() methods is a regular expression. You can use a regular expression to remove a pattern from a string.

Note: You need to use double quotes to indicate literal string values when you use the replace() methods. If you use single quotes, then the JRE assumes you’re indicating a character constant and you’ll get an error when you compile the program.

Remove a Character from a String in Java

You can remove all instances of a character from a string in Java by using the replace() method to replace the character with an empty string. The following example code removes all of the occurrences of lowercase “ a ” from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replace("a", ""); 

Remove Spaces from a String in Java

You can remove spaces from a string in Java by using the replace() method to replace the spaces with an empty string. The following example code removes all of the spaces from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replace(" ", ""); 

Remove a Substring from a String in Java

You can remove only the first occurrence of a character or substring from a string in Java by using the replaceFirst() method to replace the character or substring with an empty string. The following example code removes the first occurrence of “ ab ” from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replaceFirst("ab", ""); 

Remove all the Lowercase Letters from a String in Java

You can use a regular expression to remove characters that match a given pattern from a string in Java by using the replace.All() method to replace the characters with an empty string. The following example code removes all of the lowercase letters from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replaceAll("([a-z])", ""); 

Remove the Last Character from a String in Java

There is no specific method to replace or remove the last character from a string, but you can use the String substring() method to truncate the string. The following example code removes the last character from the given string:

String str = "abc ABC 123 abc"; String strNew = str.substring(0, str.length()-1); 

Try it out

The following example file defines a class that includes all of the method examples provided in this article, and prints out the results after invoking each method on the given string. You can use this example code to try it out yourself on different strings using different matching patterns and replacement values.

If you have Java installed, you can create a new file called JavaStringRemove.java and add the following code to the file:

 public class JavaStringRemove  public static void main(String[] args)  String str = "abc ABC 123 abc"; // Remove a character from a string in Java System.out.println("String after removing all the 'a's = "+str.replace("a", "")); // Remove spaces from a string in Java System.out.println("String after removing all the spaces = "+str.replace(" ", "")); // Remove a substring from a string in Java System.out.println("String after removing the first 'ab' substring = "+str.replaceFirst("ab", "")); // Remove all the lowercase letters from a string in Java System.out.println("String after removing all the lowercase letters = "+str.replaceAll("([a-z])", "")); // Remove the last character from a string in Java System.out.println("String after removing the last character = "+str.substring(0, str.length()-1)); > > 

Compile and run the program:

You get the following output:

Output
String after removing all the 'a's = bc ABC 123 bc String after removing all the spaces = abcABC123abc String after removing the first 'ab' substring = c ABC 123 abc String after removing all the lowercase letters = ABC 123 String after removing the last character = abc ABC 123 ab

Each method in the JavaStringRemove example class operates on the given string. The output shows that the characters specified in each method have been removed from the string.

Conclusion

In this article you learned various ways to remove characters from strings in Java using methods from the String class, including replace() , replaceAll() , replaceFirst() , and substring() . Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

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