【发布时间】:2019-07-10 09:43:42
【问题描述】:
我需要使用指定字符串片段中的字符替换此 TextLine 中 start(包括)和 end(不包括,即索引 end-1 之前的字符)之间的字符的 replace 方法。我不能直接或间接使用 StringBuffer 类的 replace(int start, int end, String fragment) 方法。我正在尝试制作 eLine.replace(0, 3, "abc");或 eLine.replace(0, 3, "abc");工作。
我尝试创建一个类似于 StringBuffer 类的替换方法,但没有成功。我想不出另一种方法来进行这样的替换,这就是我被卡住的原因。如果有其他方法,请给我一个例子或解决方案。
public int length;
public char[] characters;
public class TextLineTester {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a line of text.");
String text = input.nextLine();
EditableTextLine eLine = new EditableTextLine(text);
Scanner strCharsInput = new Scanner(System.in);
System.out.println("Enter string of characters.");
String str = strCharsInput.nextLine();
eLine.replace(0, 3, "abc");
eline.replace(0, str.length(), "abc"); // suppose to replace all occurrences of string eLine with the string ”abc”and print the modified eLine
System.out.println(eLine.toString());
}
}
public void replace(int start, int end, String fragment) {
if (end > length) {
end = length;
}
int fragmentLength = fragment.length();
int newLength = length + fragmentLength - (end - start);
ensureCapacityInternal(newLength);
System.arraycopy(characters, end, characters, start +
fragmentLength, length - end);
fragment.getChars(0,0, characters, start);
length = newLength;
}
public EditableTextLine(String line) { // creates EditableTextLine object
length = line.length();
characters = new char[DEFAULT_SIZE * 2];
characters = line.toCharArray();
}
public String toString() {
return "Characters: " + new String(characters);
}
}
This is the error I get from this current replace method.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at edu.uga.cs1302.txtbuff.EditableTextLine.replace(EditableTextLine.java:109)
at edu.uga.cs1302.test.TextLineTester.main(TextLineTester.java:36)
Input: ABCDEFG
After eLine.replace(0, 3, "abc"), Output will be
Output: abcBCDEFG
Another example:
Input: AB678CDEFGHIJK12345
eLine.replace(2,5,”XY”); // line is now ”ABXYCDEFGHIJK12345”
【问题讨论】:
-
String是不可变的。因此,您需要返回新值并将其分配到某处。这看起来也比执行replace所需的代码多。取初始匹配之前的子字符串,取之后的子字符串和替换值;将三个部分连接在一起。 -
听起来像是家庭作业,您应该完全自己完成以充分利用它。但是,冷你添加了一些输入和输出的例子,因为我不明白任务是什么。它是在位置 3 处截断输入字符串并添加“abc”,还是打算用循环通过“abc”的字符替换 3 之后的所有字符?例子胜于雄辩。
-
抱歉,我将编辑一个示例,是的,这是作业。我试图找到解决方案,但不幸的是,我没有成功。所以,我现在在这里只是寻求一些帮助或一些关于如何使用替换方法的提示。假设在任何位置切断输入字符串并添加“abc”字符串。
-
如果这是家庭作业,请说出来。
-
哦,好吧,明白了,我的错。我以后会这样做的。
标签: java