Remove all occurrences of char from string
To remove all occurrences of a particular character from a string, you can use the replace() method. This method takes two arguments: the string to be replaced, and the string to replace it with. If you pass an empty string as the second argument
To remove all occurrences of a particular character from a string, you can use the replace() method. This method takes two arguments: the string to be replaced, and the string to replace it with. If you pass an empty string as the second argument, all occurrences of the first argument will be removed from the original string.
Here is an example:
// Remove all occurrences of the character 'a' from the string 'banana'
String str = "banana";
str = str.replace("a", "");
System.out.println(str);The output will be: bnn.
You can also use a loop to iterate over the characters in the string and build a new string with only the characters you want to keep. Here is an example:
// Remove all occurrences of the character 'a' from the string 'banana'
String str = "banana";
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (c != 'a') {
sb.append(c);
}
}
System.out.println(sb.toString());The output will be the same: bnn.