Java string remove all char

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.

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.

Читайте также:  Create html form with css

References:

Источник

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.

Читайте также:  Пустые сервера awp css v34

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.

Источник

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)

Источник

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