1
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?

rishabh9
  • 13
  • 2

3 Answers3

2

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);
user2004685
  • 9,548
  • 5
  • 37
  • 54
2

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';
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
  • 1
    If I'm not wrong then it should be`StringBuilder myName = new StringBuilder(str);` instead of `StringBuilder myName = new StringBuilder("str");` – user2004685 Feb 04 '16 at 07:18
0
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

Rahul Bhawar
  • 450
  • 7
  • 17