Java – adds a char to the string at position X
                                        
                    •
                    Java                                    
                public String addLetter(char letter,int position,char[] word){
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;
    }else{
    }
    return new String(newWord);
}
I'm trying to create a method that adds a letter to a string and returns it So far, I've been able to add a character before a string, but I'm not sure how to do this at the middle / end Under the if condition, I push every letter to the back, so there is room for new letters in front But if I want to add something in the middle, any hint, I don't know what to do?
Solution
You can do the following:
Convert char array to string
String b = new String("Tutorial");
Then create StringBuilder
StringBuilder str = new StringBuilder(b);
   System.out.println("string = " + str);
   // insert character at offset 8
   str.insert(8,'s');
   // print StringBuilder after insertion
   System.out.print("After insertion = ");
   System.out.println(str.toString());// this will print Tutorials
                
                            The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
                        
                                            
                        THE END
                    
                    
                    
                                                        二维码
                        
                        
                                                
                        