【发布时间】:2016-01-25 21:09:04
【问题描述】:
我想完成一个可以接受文本文件并缩小大小的程序。到目前为止,它替换了所有出现的双字符,现在我想用“1”替换“ou”。
我尝试过使用 if 语句,但似乎效果不佳。
我的方法如下:
public String compressIt (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
String ou = "ou";
StringBuilder output = // the output
new StringBuilder(length);
// loop over every character in input
while(ix < length)
{
// read character at actual index then increments the 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 (input.charAt(ix) == 'o' && input.charAt(++ix) == 'u' && ix < length - 1)
{
output.append("1");
}
// 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();
}
我指的是这行代码。
if (input.charAt(ix) == 'o' && input.charAt(ix + 1) == 'u')
{
output.append("1");
}
我想要做的:替换字符。我得到了一个包含“爱丽丝梦游仙境”的文本文件。当我遍历所有字符时看到一个“o”和一个“u”(如“你”),我想替换这些字符,使其看起来像:“Y1”。
问候
【问题讨论】:
-
不应该是
++ix吗?开头ix的值是多少,字符串有多长? -
首先,我认为您的意思是执行
++ix而不是ix++- 就像您现在拥有的那样,您每次都检查相同的索引,并且仅在之后 i> 递增ix的语句。但是一旦你解决了这个问题,如果input是一个以o结尾的字符串会发生什么?即if (charAt(ix) == 'o')为真,ix是字符串的最后一个索引?或者就此而言,如果ix本身超过最后一个索引,由于您可能处于循环的先前迭代,会发生什么? -
哦,我想你只想要
ix + 1,而不是++ix或ix++(它们都修改了ix的值)。 -
我确实尝试了 ix + 1,这给了我同样的例外:-/
-
查看更新版本。我插入了整个方法以避免误解
标签: java arrays string char stringbuilder