So I am trying to remove all the x’s from this string! Of course I can use replaceAll but I want it to remove one by one each x and then print it! But it keeps either erroring out or I just can’t seem to remove it! Of course I know how to find the x but idk how to remove afterwards!
JavaScript
x
public class Test1
{
public static void main(String[] args)
{
String message = "Ix lovex youxxx";
System.out.println(message);
for(int x = 0 ; message.length() > 0 ; x++){
String v = message.substring(x, x+1);
if (v.indexOf("x") > -1){
String w = message.substring(v, v+1);
}
System.out.println(message);
}
}
}
Advertisement
Answer
You could work with StringBuilder
, which has an inbuilt method deleteCharAt
.
JavaScript
public static void main(String[] args) {
String msg = "Ix lovex youxxx";
char toExtract = 'x';
StringBuilder sb;
System.out.println(msg);
while (msg.indexOf(toExtract) != -1) {
sb = new StringBuilder(msg);
int index = msg.indexOf(toExtract);
sb.deleteCharAt(index);
msg = sb.toString();
System.out.println(msg);
}
}
Output:
JavaScript
Ix lovex youxxx
I lovex youxxx
I love youxxx
I love youxx
I love youx
I love you
Explanation:
As long as the string msg
still has the character to extract, a StringBuilder
is made containing the current message, the first index is removed and then saved back to msg
and printed.