Replacing all non letters with symbol * in string
My program only replaces the last non letter in string. Could someone help me:)?
Code:
Write a Java method to replace all non-letters in a given string s by symbol '*'.
public static String asenda (String s)
Code:
package soned;
public class soneExample3 {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(asenda(new String("H'o.m-m i_k")));
}
public static String asenda(String s) {
String result ="";
for(int i=0;i<s.length();i++) {
if(!Character.isLetter(s.charAt(i))) {
result = s.replace(s.charAt(i), '*');
}
}
return result;
}
}
Re: Replacing all non letters with symbol * in string
You're halfway there: you have to iterate over all characters in the String; if the current character is a letter you simply append it to the result; if it isn't a letter you append a '*' character to the result instead. Something like this:
Code:
char current= s.charAt(i);
if (Character.isLetter(current)) result+= current;
else result+= '*';
The code snippet above should be embedded in the for-loop body of your code.
kind regards,
Jos
ps. I removed your duplicate thread.
Re: Replacing all non letters with symbol * in string