Java string replace last symbol

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.

Источник

Java — replace last character in string

Wallace

Problem

I would like to change string ABC into ABD — change the last letter from ‘C’ to ‘D’.

Explanation with code, I have:

Solutions

Example 1

String text = "ABC"; String substring = text.substring(0, text.length() - 1); // AB String replaced = substring + "D"; System.out.println(text); // ABC System.out.println(replaced); // ABD
  1. To make ‘AB’ from our string we use the String substring method with 2 parameters
    The first parameter is beginIndex and the second parameter is endIndex. EndIndex is the entire length of our string minus 1 letter to remove the last letter.
  2. We add the letter we want at the end of the string — in our case it’s ‘D’
  3. As expected we replaced the last letter from C to D.

Example 2

Let’s visualize this problem on a string with digits. We want to replace the last letter of string ‘123’ with digit ‘4’ to have string ‘124’.

String text = "123"; String substring = text.substring(0, text.length() - 1); // 12 String replaced = substring + "4"; System.out.println(text); // 123 System.out.println(replaced); // 124

Example 3

In the below example, we are gonna take a look at how to create our own utility method to help us to replace the last letter of the string. The below example have the utility method replaceLastLetter() which takes our string as the first parameter and our new letter as second parameter. As the result of the utility method, we get a string with replaced last letter. The below example takes the string ‘ABC’ and replaces the last letter ‘C’ into ‘D’ and the result is ‘ABD’.

public class Example < public static String replaceLastLetter(String text, String newLetter) < String substring = text.substring(0, text.length() - 1); // ABC ->AB return substring + newLetter; // ABD > public static void main(String[] args) < String text = "ABC"; String newLetter = "D"; String replaced = replaceLastLetter(text, newLetter); System.out.println(text); // ABC System.out.println(replaced); // ABD >>

Example 4

This example is similar to example 3, but with the difference that we take character as the second parameter, not String type. In this example, we use the fact that in java we can concatenate strings with characters with the operator ‘+’.

The rest of the logic works in the same way.

public class Example < public static String replaceLastLetter(String text, char newLetter) < String substring = text.substring(0, text.length() - 1); // ABC ->AB return substring + newLetter; // ABD > public static void main(String[] args) < String text = "ABC"; char newLetter = 'D'; String replaced = replaceLastLetter(text, newLetter); System.out.println(text); // ABC System.out.println(replaced); // ABD >>

References

Источник

How to Remove the Last Character of a String?

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this quick tutorial, we’re going to explore different techniques for removing the last character of a String.

2. Using String.substring()

The easiest way is to use the built-in substring() method of the String class.

In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character. We can achieve that by calling String‘s length() method, and subtracting 1 from the result.

However, this method isn’t null-safe, and if we use an empty string, this is going to fail.

To overcome issues with null and empty strings, we can wrap the method in a helper class:

public static String removeLastChar(String s)

We can refactor the code, and use Java 8:

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

3. Using StringUtils.substring()

Instead of reinventing the wheel, we can use the StringUtils class from the Apache Commons Lang3 library, which offers helpful String operations. One of them is a null-safe substring() method, which handles exceptions.

To include StringUtils, we have to update our pom.xml file:

 org.apache.commons commons-lang3 3.12.0 

StringUtils.substring() requires three parameters: a given String, an index of the first character (in our case it will be 0 always), and the index of the penultimate character. Again, we can simply use the length() method and subtract 1:

String TEST_STRING = "abcdef"; StringUtils.substring(TEST_STRING, 0, TEST_STRING.length() - 1);

Yet again, this operation isn’t null-safe. It’ll work fine with empty Strings though.

4. Using StringUtils.chop()

The StringUtils class provides the chop() method, which works well with all edge scenarios: empty and null Strings.

It’s very easy to use, and requires only one parameter: the String. Its sole purpose is to remove the last character, nothing more, nothing less:

StringUtils.chop(TEST_STRING);

5. Using Regular Expression

We can also remove the last character (or any number of characters) from a String by making good use of regular expressions.

For example, we can use the replaceAll() method of the String class itself, which takes two parameters: the regular expression and the replacement String:

Note that, because we’re calling a method on the String, the operation isn’t null-safe.

Also, replaceAll() and regex expressions can be complex at first sight. We can read more about regex here, but to make the logic a bit more user-friendly, we can wrap it in a helper class:

public static String removeLastCharRegex(String s)

Note that if a String ends with a newline, then the above method will fail as “.” in regex matches for any character except for line terminators.

Finally, let’s re-write the implementation with Java 8:

public static String removeLastCharRegexOptional(String s) < return Optional.ofNullable(s) .map(str ->str.replaceAll(".$", "")) .orElse(s); >

6. Conclusion

In this brief article, we discussed different ways of removing only the last character of a String, some manual and some ready out of the box.

If we need more flexibility, and we need to remove more characters, we can use the more advanced solution with regular expressions.

As always, the code used throughout the article can be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Читайте также:  Text outline with css
Оцените статью