To insert a character at a specific position in a string in Java, you can use the substring()
method to extract the parts of the string before and after the insertion point, and then concatenate them with the new character to create a new string. Here is an example of how you might do this:
String s = "abcdef"; char c = 'X'; int n = 3; String t = s.substring(0, n) + c + s.substring(n); // t is "abXdef"
This code creates a new string t
by extracting the substring from the beginning of the string up to the insertion point, concatenating it with the new character 'X'
, and then concatenating it with the substring from the insertion point to the end of the string. The resulting string will be "abXdef".
You can also use the StringBuilder
class to insert a character at a specific position in a string. The StringBuilder
class provides a mutable sequence of characters that you can use to build a string efficiently. Here is an example of how you might use StringBuilder
to insert a character at a specific position in a string:
String s = "abcdef"; char c = 'X'; int n = 3; StringBuilder sb = new StringBuilder(s); sb.insert(n, c); // sb is "abXcdef" String t = sb.toString(); // t is "abXcdef"
This code creates a StringBuilder
object from the string "abcdef"
, inserts the character 'X'
at position 3 using the insert()
method, and then converts the StringBuilder
object to a string using the toString()
method. The resulting string will be "abXcdef".
Keep in mind that strings in Java are immutable, which means that you cannot modify a string directly. If you need to modify a string, you will need to create a new string or use a mutable data structure like StringBuilder
.