Java string delete one character

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.
Читайте также:  Python dict добавление значения

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.

Источник

How to Remove the First Character of a String in Java

In Java, a string is represented using the String class found in java.lang package. It is the most frequently used class in the Java library. Every string we construct in Java is an object of the type String. One thing to keep in mind about string objects is that they will not be modified after their creation. However, there exist chances that you need to do other operations on a String, such as removing characters.

This tutorial will specifically discuss the method for removing the string’s first character in Java.

How to Remove the First Character of a String in Java?

In Java, you can remove the first character of a String by utilizing:

We will now check out each of the above-given methods one by one!

Method 1: Remove the First Character of a String Using substring() Method

To remove the string’s first character, use the Java String class “substring()” method. You can also use this method for deleting the string’s first and the last character at once. Since Strings are immutable, the resultant substring should be stored in a new String type variable.

The general syntax of the substring() method is given as:

Here, the substring() method takes two parameters, “start” and “end”; the second parameter is optional. This method removes the starting and ending characters of the String and returns the resultant substring.

Though, if you intend to remove only the first character of a String, then you can pass the starting index as follows:

Have a look at the below-given example to understand the stated concept.

We will create a variable with the name “str” and print its value using the “System.out.println()” method:

Then, we will pass “1” as the starting index parameter to the “substring()” method. This operation returns a substring having all characters of the original String excluding the first one:

Lastly, we will again utilize the System.out.println() method to display the resultant String:

The output shows that the first letter of the “Linuxhint” String is successfully removed and the substring() method returned “inuxhint”:

Method 2: Remove the First Character of a String Using StringBuilder.deleteCharAt() Method

Another method to remove the string’s first character is the “deleteCharAt()” method. This method belongs to the “StringBuilder” class. Without creating new objects, StringBuilder allows the user to add or remove characters from strings because StringBuilder is mutable.

The syntax of the “deleteCharAt()” method is given as below:

It accepts only one parameter and deletes the character present at the specified index.

We will use the same string “str” that is created in the above-mentioned example. Now, we will create an object named “sbStr” of the StringBuilder class and pass “str” as a parameter:

Then, call the “deleteCharAt()” method and pass “0” as an argument to remove the first characters of the given string:

At last, print the substring using the “System.out.println()” method:

Method 3: Remove the First Character of a String Using StringBuffer.delete() Method

The “delete()” method belongs to the “StringBuffer” class. This “StringBuffer.delete()” method is also used to remove the string’s first character in Java.

The syntax of the method delete() of the StringBuffer class is:

It takes two parameters, “startindex” and “endindex”, and returns the substring after deleting the characters specified in the given range.

First, we will create an object named “sbStr” of the StringBuffer class by passing a string “str” in it as an argument:

Then, we call the “delete()” method and pass “0” as the start index and “1” as the end index:

Finally, print the resultant substring on console:

As you can see, we have successfully removed the first letter of the “Linuxhint” string using the delete() method:

We have compiled all the essential instructions related to removing the first character of a string in Java.

Conclusion

For removing the string’s first character, you can use three methods: String.substring(), StringBuilder.deleteCharAt(), or StringBuffer.delete() method. String.substring() is significantly faster than other mentioned methods. It returns a new String with an updated starting and ending index. In this tutorial, we explained the methods for removing a string’s first character in Java.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

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