Question:
How to remove all occurrences of a letter from a string?
Answer:
Use a for loop and compare each character of the string to see if it matches the letter that needs to be removed. Build a new string based on the results.
Use the String.replace() method.
Use the String.replace() method.
Code:
public class RemoveChars { public static void main(String[] args) { String str1 = "axbxcxdxex"; String str2 = ""; String str3 = ""; // using a for loop for (int i = 0; i < str1.length(); i++) { if (str1.charAt(i) != 'x') { str2 = str2 + str1.charAt(i); } } // using a for String.replace() str3 = str1.replace( "x", ""); System.out.println(str1); System.out.println(str2); System.out.println(str3); } }
Output:
$ java RemoveChars axbxcxdxex abcde abcde