-
Removing characters
So I'm trying to take a string ex. 'Lewd did I live, & evil I did dwel.' and remove all the spaces and special characters so that it just reads 'lewddidiliveevilididdwel' Here's what I have so far...I found this code on a site and it works for removing one character, but how would I edit it so it removes multiple characters? I tried adding more loops and editing it, but haven't been able to make it work. Someone help me out? Code:
public static String removeChar(String hello, char a)
{
String x = "";
for (int i = 0; i < hello.length(); i ++)
{
if (hello.charAt(i) != a)
{
x += hello.charAt(i);
}
}
return x;
}
-
Code:
String s = "Lewd did I live, & evil I did dwel";
System.out.println("s = " + s);
char space = ' ';
s = removeChar(s, space);
System.out.println("s = " + s);
String s2 = "Replaces each substring of this string that " +
"matches the literal target sequence with the " +
"specified literal replacement sequence." +
System.out.println("s2 = " + s2);
s2 = s2.replace(" ", "");
System.out.println("s2 = " + s2);
-
Thanks, I understand how it works, but how do I use that in my code?
-
how do I use that in my code?
You can use the String replace method in your code. Or you can use the replaceChar method or you can use the loop from the replaceChar method in your code.