In the below program, I'm trying to replace a string and trying to assign it to the same variable. But in Java, the Strings are immutable. So once created, we cannot able to modify it. But here I can be able to modify. Not sure whether my understanding is correct. Can anyone help me?
public static void main(String[] args) {
String s = "1234504";
s = s.replaceAll("0", "");
int count = 0;
for(int i = 0; i< s.length() ; i++){
if(Character.isDigit(s.charAt(0))){
count++;
}
}
System.out.println("Number of digits in string");
System.out.println(count);
}
replaceAllwhich support regex. It is better to callreplaceinstead since you are safer to not face problems when your literal will contain regex metacharacters like + * ^ $ and others. Both methods will replace all occurrences of searched part in string. Only difference between these methods is regex support.