LuftWoofe LuftWoofe - 1 year ago 74
Java Question

Add a char into a string at position x

public String addLetter(char letter, int position, char[] word){
char[]newWord = new char[word.length+1];

if(position == 0){
for(int i = position+1; i<word.length+1; i++){
newWord[i] = word[i-1];
newWord[position] = letter;

return new String(newWord);

I'm trying to create a method where it adds an letter to a string, then returns it. So far I've been able to add a character at the front of the string, but I'm not quite sure how to do that in the middle/end. Inside the if-condition I'm pushing every letter a slot behind, so there's room for the new letter in the front. However I don't know what to do if I'm gonna add something in the middle, any tips?

Answer Source

you can make something like below :

convert your char array to string

String b = new String(word);

then create StringBuilder

 StringBuilder str = new StringBuilder("Tutorial");
   System.out.println("string = " + str);

   // insert character value at offset 8
   str.insert(8, 's');

   // prints StringBuilder after insertion
   System.out.print("After insertion = ");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download