我正试图为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();
}
});所以我想要做的是:我想找到两个字符相等的所有单词,如果它们被放在一边(比如‘接受’)。当if语句为真时,我希望替换两个相等字符的第一个字母,因此它看起来是:'T2ok‘。
我尝试了很多东西,我得到了一个ArrayOutOfbounds,StringOutOfbounds,等等,一直.
希望有人有一个很好的答案:)
问候
发布于 2016-01-14 11:42:23
创建压缩一个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);我认为这是做你想做的事最有效的方法。
发布于 2016-01-14 11:59:18
试试这个:
StringBuilder sb = new StringBuilder();
String line;
try(BufferedReader reader = new BufferedReader(new FileReader(newFile)))
{
while ((line = reader.readLine()) != null)
{
if (!line.isEmpty()) {
//clear states
boolean matchedPreviously = false;
char last = line.charAt(0);
sb.setLength(0);
sb.append(last);
for (int i = 1; i < line.length(); i++) {
char c = line.charAt(i);
if (!matchedPreviously && c == last) {
sb.setLength(sb.length()-1);
sb.append(2);
matchedPreviously = true;
} else matchedPreviously = false;
sb.append(last = c);
}
System.out.println(sb.toString());
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}此解决方案只使用一个循环,但只能找到长度为2的事件。
https://stackoverflow.com/questions/34788047
复制相似问题