Removing character from string Java

Sometimes we have to remove a character from a string in the java program. But java String class doesn’t have the remove() method. So how would you achieve this? This Java tutorial will show you how to remove a character from a string. The following are some built-in functions for removing a specific character from a string.

  • replace function
  • deleteCharAt function
  • substring function

Employ the replace function in removing a character from a string in Java

In Java, you may use the replace function to remove a specific character from a string. The replace function has two parameters: one for the character to be removed and one for the empty String. Also, the replace function replaces a character with an empty string, resulting in removing a specific character provided together with an empty string. The following is an example of using Java’s replace function to remove a character from a string.

public class CodeRemoveCharacter
{
    public static void main(String[] args)
    {
        String stringVar = "Hello Codeunderscored";
        System.out.println("The string before removing character: " + stringVar);
        MyString = stringVar.replace(" ", "");
        System.out.println("The string after removing character: " + stringVar);
    }
}

We delete the whitespace between Hello and Codeunderscored in the code above. White space is passed along with the empty String, and the white space is replaced with the empty String, or the Hello World text is removed. The following is the code’s output.

The String before removing character: Hello Codeunderscored
The String after removing character: HelloCodeunderscored

Looking at the String class, we’ll have to replace() methods with many versions. Let’s look at the overloaded replace() methods in the String class.

replace(char oldChar, char newChar)

Replaces all occurrences of oldChar in this String with newChar and returns a string.

replace(CharSequence target, CharSequence replacement)

This String’s substrings that match the literal target sequence are replaced with the literal replacement sequence supplied.

replaceFirst(String regex, String replacement)

Replaces the first substring of this text with the specified replacement if it matches the given regular expression.

replaceAll(String regex, String replacement)

Replaces each substring of this String with the specified replacement if it matches the given regular expression. So can we use replace(‘x’,”);? You will get a compiler error as an Invalid character constant if you try this. So we will have to use other replacement methods that take String because we can specify “” as empty String to be replaced.

Example: Java String Remove Character

The code snippet below demonstrates how to delete all occurrences of a character from a string.

String str = "Codeunderscored";
String strNew = str.replace("C", ""); // strNew is 'odeunderscored'

Example: Java Remove substring from String

Let’s look at getting rid of the first instance of “ed” in the String.

String str = "Codeunderscored";
String strNew = str.replaceFirst("ed", ""); // strNew is 'Codeunderscor'

Take note of the word “replaceAll” and replaceFirst. We can utilize the first method’s first argument, a regular expression, to delete a pattern from a string. The code below removes all lowercase letters from the String.

String str = "Codeunderscored";
String strNew = str.replaceAll("([a-z])", ""); // strNew is 'C'

Example: Java Remove Spaces from String

String str = "Codeunderscored users use Java extensively";
String strNew = str.replace(" ", ""); //strNew is 'CodeunderscoredusersuseJavaextensively'

Use the deleteCharAt method for removing a character from a string in Java.

The StringBuilder class has a member function called deleteCharAt() that is used to remove a character from a string in Java. If we want to use the deleteCharAt method to remove a specific character from a string, we must first know where that character is in the String.

The deleteCharAt() method retrieves the character’s position we wish to remove from the String. When using the deleteCharAt method to remove a character from a string, we need to know where that character is in the String. The following is an example of using Java’s deleteCharAt function to remove a character from a string.

public class CodeRemoveCharacter
{
   public static void main(String[] args)
   {
        StringBuilder stringVar = new StringBuilder("Hello Codeunderscored");
        System.out.println("The string before removing character: " + stringVar);
        MyString = MyString.deleteCharAt(5);
        System.out.println("The string after removing character: " + stringVar);
   }
}

We eliminate the white space between Hello and Codeunderscored in the above code. Because the index in Java starts at 0, we pass the location of the white space, which is 5, in the text Hello Codeunderscored. The following is the code’s output.

The String before removing character: Hello Codeunderscored

The String after removing character: HelloCodeunderscored

Engage the substring method for the removal of a character from a string in Java

In Java, you may use the substring method to extract a character from a string. We must supply the starting position and the position before the deleting character to the substring method to remove a specific character. The String is then concatenated from our character’s location in the String.

The substring method divides a string into two parts based on the starting and ending indexes, then concatenates the two parts by overwriting the character we want to remove from the String. The following is an example of utilizing Java’s substring function to delete a character from a string.

public class CodeRemoveCharacter
{  
    public static void main(String[] args)
    {  
        String stringVar = "Hello Codeunderscored";
        int Position = 5;
        System.out.println("The string before removing character: " + stringVar);
        MyString = stringVar.substring(0,Position) + stringVar.substring(Position+1);
        System.out.println("The string after removing character: " + stringVar);  
    }

We eliminate the white space between Hello and Codeunderscored in the code above. We know where the white space is in a variable with a value of 5. Using the substring method, we split the Hello Codeunderscored string from the 0th to the 5th position and concatenate the remaining parts of the String from the 6th position. We are removing the white space from the Hello Codeunderscored due to this.

The following is the code’s output.

The String before removing character: Hello Codeunderscored
The String after removing character: HelloCodeunderscored

Removing the string’s last character in Java

Although you can use the string substring method, there is no technique for replacing or removing the last character from a string.

String strVar = "Hello Codeunderscored!";
String strNewVar = str.substring(0, strVar.length()-1); //strNewVar is 'Hello Codeunderscored'

Example: Removing a character from a string in Java

You may find the whole Java class for the samples presented above here.

package com.codeunderscored.examples;

public class JavaStringRemove {

	public static void main(String[] args) {
		String str = "CodeUNDERscored";

		System.out.println("String after Removing 'a' = "+str.replace("C", ""));
		
		System.out.println("String after replacing 'ed' = "+str.replaceFirst("ed", ""));

		System.out.println("String after replacing all small letters = "+str.replaceAll("([a-z])", ""));
	}

}

The following is the output of the program:

String after Removing 'C' = odeUNDERscored
String after Removing replacing 'ed' = odeUNDERscor
String after replacing all small letters = UNDER

Remove the beginning and last character of a string in Java

The aim is to develop a Java program that removes the beginning and last character of the String and prints the modified String, given the string str.

Input: str = "CodeUnderscored"
Output: odeUnderscore

Explanation:

The given String’s first character is ‘C,’ and the last character of the given String is ‘d’. After removing the string’s first and last character, the String becomes “odeUnderscore.”

Input: str = "JavaCode"
Output: avaCod

Explanation:

The given string’s first character is ‘J,’ and the last character of the given String is ‘e’. After removing the first and final character of a string, the String becomes “JavaCode.”

Approach 1: Use the String.substring() function

The goal is to eliminate the first and last character of a string using the String class’s substring() function. The method substring(int beginIndex, int endIndex) takes two parameters: the starting index and the ending index.

The initial character of a string appears at index zero, whereas the last character appears at index length of String – 1. Using strVar.substring(1, strVar.length() – 1), extract the substring excluding the first and last character. Print the updated String now. Below is the code implementation of the concept illustrated above.

Example: Program for removing the first and the last character of a string in Java

class Codeunderscored {

	// Function for removing both the initial and
	// the final character of a specified string

	public static String
	codeRemoveFirstandLast(String strVar)
	{

		// Removal of the initial and final character
		// in a string by using the method substring()

		strVar = strVar.substring(1, strVar.length() - 1);

		// Returns the string that has beed modified 
		return strVar;
	}

	// Driver Code
	public static void main(String args[])
	{
		// Given String strVar
		String strVar = "CodeUnderscored";

		// Print the modified string
		System.out.print(
			removeFirstandLast(strVar));
	}
}

Approach 2: Delete a character using the StringBuilder.deleteCharAt() method

The aim is to remove the first and last character of a string using the StringBuilder class’s deleteCharAt() function. The deleteCharAt() method takes an index of the character you want to remove as an argument.

  • sBuffer.deleteCharAt(str.length() – 1) deletes the last character of a string.
  • Using sBuffer.deleteCharAt(0), remove the first character of a string .

You should now print the updated String. The following is how the above strategy is put into action:

Example: Program for removing the first and the last character of a string in Java

class Codeunderscored {

	// Function to remove the first and
	// the last character of a string
	public static String
	removeFirstandLast(String str)
	{

		// Creating a StringBuilder object
		StringBuilder sBuffer = new StringBuilder(str);

		// Removing the last character
		// of a string
		sBuffer.deleteCharAt(str.length() - 1);

		// Removing the first character
		// of a string
		sBuffer.deleteCharAt(0);

		// Converting StringBuilder into a string
		// and return the modified string
		return sBuffer.toString();
	}

	// Driver Code
	public static void main(String args[])
	{
		// Given String strVar
		String strVar = "CodeUnderscored";

		// Print the modified string
		System.out.println(
			removeFirstandLast(strVar));
	}
}

Approach 3: Delete a StringBuffer using the StringBuffer.delete() method

The aim is to remove the initial and last character of a string using the StringBuffer class’s delete() method. The delete(start point, int endpoint) method takes the start point and the endpoint and returns the String after deleting the substring created by the parameters’ range.

  • sBuffer.delete(strVar.length() – 1, strVar.length()) removes the string’s last character.
  • Using sBuffer.delete(0,1), remove the first character in the string .

You should now print the updated String. The following is how the above strategy is put into action:

Example: Program for removing the first and the last character of a string in Java
class Codeunderscored {

	// Function for removing the initial and
	// the final characters in a specified string

	public static String
	codeRemoveFirstandLast(String str)
	{

		// Creation of a StringBuffer object
		StringBuffer sBuffer = new StringBuffer(str);

		// Removal of the string's last character
		sBuffer
.delete(str.length() - 1, str.length());

		// Removing the first character
		// of a string
		sBuffer.delete(0, 1);

		// Converting StringBuffer into
		// string & return modified string
		return sBuffer.toString();
	}

	// Driver Code
	public static void main(String args[])
	{
		// Given String str
		String strVar = "CodeUnderscored";

		// Print the modified string
		System.out.println(
			removeFirstandLast(strVar));
	}
}
Example: Removing a particular character from a string
public class CodeRemoveChar {  
  public static void main(String[] args) {  
    String str = "Codeunderscored is my site";  
    System.out.println(charRemoveAt(str, 7));  
  }  
  public static String charRemoveAt(String str, int p) {  
    return str.substring(0, p) + str.substring(p + 1);  
  }  
}  

Example: Removing Substring from String in Java

Consider an example of removing a substring from a string.

String initialString = "Code in Python Java Spring Python";
System.out.println(initialString);
 
String finalString = s1.replace("Python", "");
System.out.println(finalString)

Conclusion

In Java, we sometimes need to remove characters from a String. However, it is impossible with the String class’s remove() method.

A character can be removed from a string in various ways, including at the beginning, end, or a defined place. To delete a specific character from a string and replace it with an empty string, use the replace() method. In addition, the replace() methods of the Java String class are numerous. The latter is critical in helping remove characters from a string. The objective is to replace the value with an empty string.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *