Reputation: 13
I have a homework to do and have a problem. I have to search the "*" (star) in a string in Java (I work with Eclipse IDE) and have to delete it, but somehow my Code does not work.
class Main {
public static String starOut(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '*') {
s.replace(s.charAt(i), '');
}
}
return s;
}
public static void main(String[] args) {
String result = starOut("ab*cd");
System.out.println(result); // => "ad"
System.out.println(starOut("ab**cd")); // => "ad"
System.out.println(starOut("sm*eilly")); // => "silly"
}
}
The output should be like in the comments in the last lines
Upvotes: 0
Views: 45
Reputation: 201467
Your code doesn't even compile, there is no empty char
for ''
. I would use a StringBuilder
, start with an empty StringBuilder
and add all char
(s) that are not *
to it. Then return that as a String
. Like,
public static String starOut(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch != '*') {
sb.append(ch);
}
}
return sb.toString();
}
Alternatively, if you can use in-built methods;
public static String starOut(String s) {
return s.replaceAll("\\*", "");
}
Upvotes: 4