gpt4 book ai didi

Java 替换文本文件中的字符 - 爱丽丝梦游仙境

转载 作者:行者123 更新时间:2023-12-02 04:02:06 25 4
gpt4 key购买 nike

我正在尝试为 TextFiles 制作一个压缩器,但我在替换字符时遇到了困难。

这是我的代码:

compress.setOnAction(event ->
{
String line;
try(BufferedReader reader = new BufferedReader(new FileReader(newFile)))
{
while ((line = reader.readLine()) != null)
{
int length = line.length();
String newLine = "";


for (int i = 1; i < length; i++)
{
int c = line.charAt(i);

if (c == line.charAt(i - 1))
{

}
}
}

}
catch (IOException ex)
{
ex.printStackTrace();
}
});

所以我想做的是:我想找到两个字符相等的所有单词,如果它们放在一边(例如“Took”)。当 if 语句为 true 时,我想替换两个等于字符的第一个字母,因此它看起来像:“T2ok”。

我尝试了很多方法,但总是遇到 ArrayOutOfbounds、StringOutOfbounds 等等...

希望有人有一个很好的答案:-)

问候

最佳答案

创建一个压缩一个String的方法,如下所示:
使用 while 循环遍历每个字符。在另一个嵌套 while 循环中对重复项进行计数,该循环在找到重复项时增加当前索引,并跳过将它们写入输出。此外,这还计算它们的出现次数。

public String compress(String input){
int length = input.length(); // length of input
int ix = 0; // actual index in input
char c; // actual read character
int ccounter; // occurrence counter of actual character
StringBuilder output = // the output
new StringBuilder(length);

// loop over every character in input
while(ix < length){
// read character at actual index then inc index
c = input.charAt(ix++);
// we count one occurrence of this character here
ccounter = 1;
// while not reached end of line and next character
// is the same as previously read
while(ix < length && input.charAt(ix) == c){
// inc index means skip this character
ix++;
// and inc character occurence counter
ccounter++;
}
// if more than one character occurence is counted
if(ccounter > 1){
// print the character count
output.append(ccounter);
}
// print the actual character
output.append(c);
}
// return the full compressed output
return output.toString();
}

现在您可以使用此方法使用 java8 技术创建文件输入到输出流。

// create input stream that reads line by line, create output writer
try (Stream<String> input = Files.lines(Paths.get("input.txt"));
PrintWriter output = new PrintWriter("output.txt", "UTF-8")){
// compress each input stream line, and print to output
input.map(s -> compress(s)).forEachOrdered(output::println);
} catch (IOException e) {
e.printStackTrace();
}

如果你真的想的话。您可以删除输入文件并随后重命名输出文件

Files.move(Paths.get("output.txt"), Paths.get("input.txt"),StandardCopyOption.REPLACE_EXISTING);

我认为这是做你想做的事情最有效的方式。

关于Java 替换文本文件中的字符 - 爱丽丝梦游仙境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34788047/

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