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 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?
One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer.
Method 1: Add char to String Using Concatenation Operator “+” The easiest and most commonly used method to add char to a String is the Concatenation operator “+”. It concatenates the character to a String.
The next method of inserting the characters into a string is using a combination of a list(), insert(), and join() built-in functions of Python. By using this combination, we can convert the string into a list with the list() function and add the string at the targeted position with the insert() function.
C++ '+' operator for String Concatenation C++ '+' operator can be used to concatenate two strings easily. The '+' operator adds the two input strings and returns a new string that contains the concatenated string.
You can make something like below :
Convert your 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
You could go this way too:
public String addLetter(char letter, int position, char[] word) {
return new StringBuilder(new String(word)).insert(position, letter).toString();
}
You could do something like this:
string = string.substring(0,x) + "c" + string.substring(x, string.length());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With