gpt4 book ai didi

Java String.replaceFirst() 问题

转载 作者:行者123 更新时间:2023-12-01 17:20:59 25 4
gpt4 key购买 nike

嗨,我正在尝试编写代码来读取包含一首诗的文件。然后它将每行中的第一个“您”更改为“我们”。我一直在尝试使用replaceFirst()、replace()、replaceAll();然而,没有一个人能够替代任何东西。

 import java.io.*;
import java.util.Scanner;//imports

public class TextEditorTester
{
private static boolean line_change;

public static void main(String[] args) throws FileNotFoundException
{
String line = "";
File inFile = new File("OldPoem.txt");
Scanner in = new Scanner(inFile);
PrintWriter out = new PrintWriter("NewPoem.txt");
while(in.hasNextLine()){
line = in.nextLine();
line.replace("you", "we");
out.println(line);
}
out.close();
File newFile = new File("NewPoem.txt");
Scanner newOne = new Scanner(newFile);
System.out.println(newOne.nextLine());
System.out.println("Expected: Have we ever tried to enter the long black branches of other lives");
}
}

最佳答案

replace 方法返回新行,它无法修改您调用它的对象。所以尝试一下:

line = line.replace("you", "we");

关于Java String.replaceFirst() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18820246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com