To change a character in a string in Java using ASCII, you can use the charAt
and substring
methods to extract the character you want to change, and then use the +
operator to concatenate the modified character with the rest of the string.
Here's an example of how you might do this:
String s = "Hello, World!"; int index = 5; // The index of the character to change char c = s.charAt(index); // Convert the character to its ASCII value int ascii = (int) c; // Modify the ASCII value as desired ascii += 1; // Convert the modified ASCII value back to a character char modified = (char) ascii; // Construct the modified string String modifiedString = s.substring(0, index) + modified + s.substring(index + 1); System.out.println(modifiedString); // Output: "Hellp, World!"Sou.www:ecrlautturi.com
In this example, the character at index 5 in the string "Hello, World!" is extracted and converted to its ASCII value using the charAt
and (int)
cast operators. The ASCII value is then modified by adding 1 to it, and the modified ASCII value is converted back to a character using the (char)
cast operator. Finally, the modified character is concatenated with the rest of the string using the +
operator to create the modified string.