I wish to convert all the lowercase letters of a user given string to '#'. But upon running the code, only the last lowercase char is getting converted. Could someone suggest a solution to this ? (I am new in java)
import java.util.Scanner;
class replaceEx{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
String s1,s2=null;
s1=s.nextLine();
for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)>='a' && s1.charAt(i)<='z')
s2=s1.replace(s1.charAt(i),'#');
}
System.out.println(s2);
}
}
Input : ABCDabcd
Output: ABCDabc#
Here:
s2=s1.replace(s1.charAt(i),'#');
What happens is: s2 becomes s1, where that char at i gets replaced with '#'.
You assume that somehow s2 remembers previous assignments. It doesn't.
In other words: your code does call:
s2=s1.replace('a','#');
s2=s1.replace('b','#');
s2=s1.replace('c','#');
s2=s1.replace('d','#');
So, s2 becomes assigned ABCD#bcd, ABCDa#cd, ABCDab#d, ABCDabc#. And as said: only that last assignment sticks. Worse: replace()
doesn't care about that index i
that you used for charAt()
. It simply replaces the first occurrence of the char to look for. In other words: if your word is "Aaba", you always keep replacing only that first 'a' with #.
In other words: your whole approach can't work, for multiple reasons.
There are multiple ways to solve this, for example to use replaceAll()
. That method also allows to use regular expressions, so that you can say (in one call) "replace all lowercase chars with #" easily.
Another approach would be: