Skip to content

Commit 9a3d2c4

Browse files
committed
feat: Modify a string by converting to char array and replacing a character
🔍 What this code does: - Converts the string `"abc"` to a character array using `toCharArray()`. - Replaces the character at index 2 (`'c'`) with `'d'`. - Converts the modified character array back to a string. - Prints the new string, which becomes `"abd"`. ✅ Why: Strings in Java are immutable. To change individual characters, convert to a char array, modify, then reconstruct the string. Signed-off-by: Somesh diwan <[email protected]>
1 parent f6c0260 commit 9a3d2c4

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed
Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
public class StringC {
2-
public static void main(String[] args)
3-
{
2+
public static void main(String[] args) {
43
String s = "abc";
54
char[] sArray = s.toCharArray();
65
sArray[2] = 'd';
@@ -10,7 +9,9 @@ public static void main(String[] args)
109
}
1110

1211
/*
13-
The toCharArray() method in Java converts a String into a char array. For example, if you have a string "abc",
12+
The toCharArray() method in Java converts a String into a char array.
13+
14+
For example, if you have a string "abc",
1415
calling toCharArray() will return a char array like this: {'a', 'b', 'c'}.
1516
1617
s.toCharArray() converts the string "abc" into a char array {'a', 'b', 'c'}.
@@ -21,13 +22,14 @@ Finally, you convert the modified char array back into a String using new String
2122
2223
Converting a String to a char array is useful when you need to manipulate individual characters in the string.
2324
24-
Strings in Java are immutable, meaning once created, they cannot be changed. However, a char array is mutable,
25-
so you can modify its elements directly.
25+
Strings in Java are immutable, meaning once created, they cannot be changed.
26+
27+
However, a char array is mutable, so you can modify its elements directly.
2628
2729
You wanted to change the third character ('c') to 'd'.
2830
2931
Since String is immutable, you first converted it to a char array using toCharArray().
3032
3133
Then, you modified the array (sArray[2] = 'd').
3234
Finally, you converted the modified char array back to a String.
33-
*/
35+
*/

0 commit comments

Comments
 (0)