我需要使用指定字符串片段中的字符替換此 TextLine 中開始(包括)和結(jié)束(不包括,即索引 end-1 之前的字符將被替換)之間的字符的替換方法。我不能直接或間接使用 StringBuffer 類的 replace(int start, int end, String fragment) 方法。我正在嘗試制作 eLine.replace(0, 3, "abc"); 或者 eLine.replace(0, 3, "abc"); 工作。我試著做了一個(gè)類似StringBuffer Class的replace方法,但是沒有成功。我想不出另一種方法來進(jìn)行這樣的替換,這就是我被卡住的原因。如果有其他方法,請(qǐng)給我一個(gè)示例或解決方案。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);}}
如何在不使用 String Buffer 類 replace() 方法的情況下替換字符串中的字符?
寶慕林4294392
2023-03-17 14:08:14