快速提问很可能非常简单。
基本上,我需要将字符串从obdurate更改为oblite。我知道我可以使用StringBuilder的方法,但我无法在初始字符串后插入任何内容。无论如何还要添加更多字符吗?
我的代码如下
public class SimpleString {
public static void main (String [] args){
StringBuilder s1 = new StringBuilder ("obdurate");
s1.delete(2, 7);
s1.replace(2, 7, "lite");
s1.insert(8,15, "ration"); //the problem line.
System.out.println(s1);
答案 0 :(得分:3)
使用StringBuilder。append(String str)
s1.append("ration");
答案 1 :(得分:1)
使用append():
s1.append("ration");
答案 2 :(得分:1)
您可以尝试以下内容:
public class SimpleString {
public static void main (String [] args){
StringBuilder s1 = new StringBuilder ("obdurate");
s1.delete(2, 7);
s1.replace(2, 7, "lite");
s1.append("ration");
System.out.println(s1);
答案 3 :(得分:0)
我需要将字符串从 obdurate 更改为删除。
将indexOf(str)
与replace(stIndx, endIndx, replacement)
功能一起使用:
StringBuilder builder = new StringBuilder("obdurate it is");
int stIndex = builder.indexOf("obdurate");
int endIndex = stIndex + "obdurate".length(); // Find the end of the replacing string
builder.replace(stIndex, endIndex, "obliteration");
无论如何都要添加更多字符?
使用strBuilder.append(String)
函数,其中strBuilder
是StringBuilder
的实例
答案 4 :(得分:0)
s1.delete(2, s1.length());
s1.append("literation");
答案 5 :(得分:0)
试试这个
public static void main(String[] args){
StringBuilder s1 = new StringBuilder ("obdurate");
s1.delete(2, 7);
s1.replace(2, 7, "lite");
s1.append("ration");
System.out.println(s1);
}
答案 6 :(得分:0)
假设你想在s1中插入一个字符串,最好的方法是
for (int start = 0, start < 7; start ++) // assuming you wanna insert a string with length 7
s1.append(" ")
// s1 = "obdurate " then now you can insert a new string easily
// you can now insert in between (i guess by using insert, you don't just want the string to be added in the end)
s1.insert(3,10, "rationa"); // s1 = "obdrationaurate";