+ 1

String assignment

For example : if : int [] ar={6,7,8} int k=0; Then: ar[k]=ar[k+1]; Same scenario in string If : string str=“678”; int k=0; Then: Str.charAt(k)=str.charAt(k+1); // this statement is getting error i.e:unexpected type required: variable Found : value Can you please tell me the solution

9th Mar 2020, 4:40 PM
Haritha Vuppula
Haritha Vuppula - avatar
3 Answers
0
Yes. String are immutable so you can't change but can create new one and replace old.. One way is: ex: use replace function String s="78"; k=0; System.out.println(s) ; s=s.replace(s.charAt(k),s.charAt(k+1)); System.out.println (s) ; Otherway, convert to equalent char array by char ch[] = s.toCharArray(); Now, you can do modifications with indexes, like you mentioned for integers.. Reform string by loops or use s= String.valueOf(ch);
9th Mar 2020, 6:24 PM
Jayakrishna 🇼🇳
0
Hi. String in java is immutable. You should consider using StringBuilder class that has method setCharAt for this purpose.
9th Mar 2020, 5:14 PM
Stephan
Stephan - avatar
0
thnq i jayakrishna garu i got the code
10th Mar 2020, 6:13 PM
Haritha Vuppula
Haritha Vuppula - avatar