Scanner s=new Scanner(System.in);
String str=s.nextLine();
str.charAt(2)='a';
I have used substr function . but can it be done without it? Why is this statement incorrect?
Strings are immutable in JAVA. You can convert it to a Character Array and then alter the characters.
String str = s.nextLine();
char[] chrArray = str.toCharArray();
chrArray[2] = 'a';
If you want a String out of it then you can do:
String finalStr = new String(chrArray);
You can use setCharAt
like this:
StringBuilder string = new StringBuilder(str);
string.setCharAt(2, 'a');
Or char[]
array:
char[] nameChars = str.toCharArray();
nameChars[2] = 'a';
StringBuilder sb =new StringBuilder(str);
System.out.println(" string is : "+sb.replace(2, 3, "a"));
sb.replace(start index,endindex,replace string)
start index ;- string start index
end index ;- end index for example if you want to replace single char then start 2 and end 3