Objective
This section we will be dealing with the removal or deletion of character on a string. A String is composed of characters thus removing characters will be an easy task. We will be showing multiple possibilities such as removal of character at a specified index. And also we will be exploring on how to remove all occurrences of a character on a string. These java programming examples will enhance these knowledge:
- Handling of Strings
- Method calling and processing
- Using String class methods
Delete a single character from a String in Java
The following example give a detail in deleting a single character from a String. As you would have noticed we have removed the character x which is on index 2. Giving an overview, a string starts it index at 0. We then call a separate method which takes a method argument string and an index. The string is the base String which we want to remove the character at specified index.
package com.javatutorialhq.java.examples; import static java.lang.System.*; /* * This basic java example source code * shows how to delete a single character from a String */ public class DeleteSingleCharExample { public static void main(String[] args) { // Declare a string object String strValue = "aaxabbccddeefff"; // call a method to delete a character String newString = deleteCharAt(strValue, 2); // print the new string value out.println("New String:" + newString); } private static String deleteCharAt(String strValue, int index) { return strValue.substring(0, index) + strValue.substring(index + 1); } }
Sample Output on how to Delete a Single Character
New String:aaabbccddeefff
Delete all occurrences of a character on a String
This might be a little hard and tricky since we are deleting all occurrences of a character. From the first example we just used substring to remove, but on this example it is easier to just call a helpful method of String class replaceAll
package com.javatutorialhq.java.examples; import static java.lang.System.*; /* * This basic java example source code * shows how to delete all occurrences of a character on a String */ public class DeleteAllOccurrencesCharacter { public static void main(String[] args) { // Declare a string object String strValue = "aaxabbccddeefff"; // call a method to delete all occurrences String newString = deleteAll(strValue, "a"); // print the new string value out.println("New String:" + newString); } private static String deleteAll(String strValue, String charToRemove) { return strValue.replaceAll(charToRemove, ""); } }
Sample Output on how to Delete all Occurrence of Character on a String object
New String:xbbccddeefff