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);
}
我试图创建一个方法,在其中为字符串添加一个字母,然后返回它。到目前为止,我已经能够在字符串的前面添加一个字符,但我不太确定如何在中间/结尾处这样做。在if条件下,我将每个字母推到后面一个插槽,所以前面有新信的空间。但是,如果我要在中间添加一些东西,任何提示,我都不知道该怎么办?
答案 0 :(得分:20)
您可以制作如下内容:
将char数组转换为字符串
String b = new String("Tutorial");
然后创建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
答案 1 :(得分:2)
你也可以这样:
public String addLetter(char letter, int position, char[] word) {
return new StringBuilder(new String(word)).insert(position, letter).toString();
}
答案 2 :(得分:0)
最简单的方法是使用2个循环:
char[] newWord = new char[word.length + 1];
for(int i = 0; i < position; i++) newWord[i] = word[i];
newWord[position] = letter;
for(int i = position + 1; i < newWord.length; i++) newWord[i] = word[i - 1];
return new String(newWord);
答案 3 :(得分:0)
使用String.substring(int startindex,int end)方法怎么样?
它应该是这样的
public static String addLetter(char letter, int position, String word){
String toSupport = "";
if(position == 0){
toSupport += letter +word;
} else {
String temp = word.substring(0, position+1);
toSupport += temp + Character.toString(letter) + word.substring(position+1, word.length());
}
return toSupport;
}
public static void main(String[] args) {
System.out.println(addLetter('a', 1, "hello"));
}
答案 4 :(得分:0)
单个循环,O(n)复杂度
public String addLetter(char letter, int position, char[] word){
char[]newWord = new char[word.length+1];
int offset = 0;
for(int i=0; i<newWord.length; i++) {
if(position == i) {
newWord[i] = letter;
offset = 1;
} else {
newWord[i] = word[i-offset];
}
}
return new String(newWord);
}
答案 5 :(得分:0)
你可以这样做,因为没有字符串操作的行移动api
public String addLetter(char letter, int position, char[] word) {
char[] newWord = new char[word.length + 1];
int i;
for (i = word.length; i >= position; i--) {
newWord[i] = word[i-1];
}
newWord[i] = letter;
while(i>0){
newWord[--i] = word[i];
}
return new String(newWord);
}
答案 6 :(得分:0)
private static String insertChar(String word, char letter, int position) {
char[] chars = word.toCharArray();
char[] newchars = new char[word.length() + 1];
for (int i = 0; i < word.length(); i++) {
if (i < position)
newchars[i] = chars[i];
else
newchars[i + 1] = chars[i];
}
newchars[position] = letter;
return new String(newchars);
}
答案 7 :(得分:0)
您可以执行以下操作:
string = string.substring(0,x) + "c" + string.substring(x, string.length());