Java string remove all characters

How to Remove Character from String in Java

Sometimes we have to remove characters from a String in Java. There is no remove() method in String class to do this.

Java Remove Character from String

Java String class has various replace() methods. We can use this to remove characters from a string. The idea is to pass an empty string as a replacement.

Let’s look at the replace() methods present in the String class.

  1. replace( char oldChar, char newChar) : This method returns a new string where oldChar is replaced with newChar. This method replaces all the occurrences of the oldChar with the newChar character.
  2. replace(CharSequence target, CharSequence replacement) : This method replaces the target substring with the replacement substring. This method replaces all the matches of target substring with the replacement substring.
  3. replaceFirst(String regex, String replacement) : This method replaces the first match of the regex with the replacement string. This method is useful when we have to replace only the first occurrence of the substring.
  4. replaceAll(String regex, String replacement) : It’s like the replaceFirst() method. The only difference is that all the occurrences of the matched regex are replaced with the replacement string.
Читайте также:  Html code with image and link

NOTE: There is no empty character constant. So we can’t use the first replace(char c1, char c2) method to remove a character from the string. We will have to use any of the other three methods by passing an empty string as a replacement.

Java String Replace Empty Character Error

Java Remove Character from String Example

Let’s look at a simple example to remove all occurrences of a character from the string.

jshell> String s1 = "Hello"; s1 ==> "Hello" jshell> s1.replace("l", ""); $26 ==> "Heo"

Java String Remove Character Example

Java Remove Substring from String Example

Let’s look at an example to remove a substring from the string.

jshell> String s1 = "Java Python Spring Python"; s1 ==> "Java Python Spring Python" jshell> String s2 = s1.replace("Python", ""); s2 ==> "Java Spring "

Java Remove Substring Regex Example

The replaceFirst() and replaceAll() methods accept regular expression as the first argument. We can use it to remove a pattern from the string. For example, remove all the lowercase characters from the string.

jshell> String s1 = "Hi Hello"; s1 ==> "Hi Hello" jshell> s1.replaceAll("([a-z])", ""); $30 ==> "H H" jshell> s1.replaceFirst("([a-z])", ""); $31 ==> "H Hello"

Remove Whitespaces from the String

Let’s look at an example to remove all the whitespaces from the string.

jshell> String s1 = "Hello World 2019"; s1 ==> "Hello World 2019" jshell> String s2 = s1.replace(" ", ""); s2 ==> "HelloWorld2019"

What if the string has tab-character?

Let’s see how to remove tab-character and whitespaces from the string.

jshell> String s1 = "Hello World\t2019"; s1 ==> "Hello World\t2019" jshell> String s2 = s1.replace(" ", ""); s2 ==> "HelloWorld\t2019" jshell> String s3 = s2.replace("\t", ""); s3 ==> "HelloWorld2019"

We can also use regex for this.

jshell> String s1 = "Hello World\t2019"; s1 ==> "Hello World\t2019" jshell> s1.replaceAll("\\s", ""); $37 ==> "HelloWorld2019"

How to Remove the Last Character from the String?

There is no method to remove the last character from the string. We can achieve this using substring() method.

jshell> String str = "Hello World!"; str ==> "Hello World!" jshell> str.substring(0, str.length()-1); $39 ==> "Hello World"

Conclusion

We don’t need remove() method to remove characters from the string. The replace() methods are good enough for this task.

References:

Источник

How to remove all special characters from String in Java? Example Tutorial

You can use a regular expression and replaceAll() method of java.lang.String class to remove all special characters from String. A special character is nothing but characters like — ! #, %, etc. Precisely, you need to define what is a special character for you. Once you define that you can use a regular expression to replace those characters with empty String, which is equivalent to removing all special characters from String. For example, suppose, your String contains some special characters e.g. «Awesome. « and you want to remove those . to reduce some excitement, you can use replaceAll(«!», «») to get rid of all exclamation marks from String.

Similarly, if you String contains many special characters, you can remove all of them by just picking alphanumeric characters e.g. replaceAll(«[^a-zA-Z0-9_-]», «») , which will replace anything with empty String except a to z, A to Z, 0 to 9,_ and dash. Let’s see a couple fo examples to remove all special characters from String in Java.

By the way, if you are a complete beginner into Regular expression and don’t understand these magical symbols then I highly recommend you join The Complete Regular Expression course for beginners course on Udemy. It’s a great course to learn everything about RegEx you want to know and it’s also very affordable, you can buy in just $10 on Udemy sales which happens every now and then.

Java Program to remove all special characters from String

Here is our sample Java program to demonstrate how you can use the replaceAll() method to remove all special characters from a String in Java. Since String is Immutable in Java, make sure you store the String returned by the replaceAll() method, this is your output i.e. String without any special characters.

You should spend some time sharing your regular expression skill, as it’s one of the powerful tools for debugging and troubleshooting. It is also one thing that separates the average programmers from good programmers. Mastering Regular Expressions is one of the great books to sharpen your regex skills.

How to remove all special characters from String in Java

public class App< public static void main(String args[]) < String text = "This - text ! has \\ /allot # of % special % characters"; text = text.replaceAll("[^a-zA-Z0-9]", ""); System.out.println(text); String html = "This is bold"; html = html.replaceAll("[^a-zA-Z0-9\\s+]", ""); System.out.println(html); > > Output Thistexthasallotofspecialcharacters b This is bold b

That’s all about how to remove all special characters from String in Java. As I said, you can use the replaceAll() method of String along with regular expression to get rid of unwanted characters. You can define characters you want or remove in the regular expression as shown in our example. Let me know if you have any doubt.

  • How to reverse String in Java without Recursion? (answer)
  • How to convert a char to String to Java? (answer)
  • How to compare two String objects in Java? (answer)
  • When to use the intern() method of String in Java? (answer)
  • How to convert Double to String in Java? (solution)
  • Top 20 String Algorithm Questions from Coding Interviews (read here)
  • How to find all permutations of a String in Java? (solution)
  • How to check if two String are Anagram in Java (answer)

Источник

Remove all non-alphanumeric characters from a String in Java

This post will discuss how to remove all non-alphanumeric characters from a String in Java.

1. Using String.replaceAll() method

A common solution to remove all non-alphanumeric characters from a String is with regular expressions. The idea is to use the regular expression [^A-Za-z0-9] to retain only alphanumeric characters in the string.

Output:

ABCDE1

You can also use [^\w] regular expression, which is equivalent to [^a-zA-Z_0-9] . It will replace characters that are not present in the character range A-Z , a-z , 0-9 , _ . Alternatively, you can use the character class \W that directly matches with any non-word character, i.e., [a-zA-Z_0-9] .

Output:

ABCD_E1

Note, this solution retains the underscore character. If you need to remove underscore as well, you can use regex [\W]|_ . Alternatively, you can use the POSIX character class \p , which matches with any alphanumeric character [A-Za-z0-9] . It is equivalent to [\p\p] .

Output:

ABCDE1

2. Using Guava

If you use the Guava library in your project, you can use its javaLetterOrDigit() method from CharMatcher class to determine whether a character is an alphabet or a digit. You can remove or retain all matching characters returned by javaLetterOrDigit() method using the removeFrom() and retainFrom() method respectively. This is demonstrated below:

Источник

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