提问人:BeyondeR 提问时间:11/9/2023 更新时间:11/9/2023 访问量:70
Java - 遍历奇数长度的字符串,一次两个连续的字符
Java - Iterate over an odd length String, two consecutive characters at once
问:
我正在逐行读取一个文件(使用BufferedReader和FileReader),并且需要获取两个连续的字符并将其存储在循环的每次迭代的两个不同变量中,但是字符串长度可以是“偶数”或“奇数”。
对于长度为“偶数”的字符串,一个简单的“偶数”检查即可完成,如下所示:
if (line.length() % 2 == 0) {
char firstChar = line.charAt(i);
char secondChar = line.charAt(i + 1);
}
但是对于“奇数”长度的字符串,除了下面的方法之外,找不到更好的方法了——
我尝试了以下“偶数”和“奇数”长度字符串:
public void readTwoChars(BufferedReader b) {
String line = null;
while ((line = b.readLine()) != null) {
for (int i = 0; i < line.length(); i += 2){
char firstChar = line.charAt(i);
char secondChar = 0;
if (i != line.length() - 1) {
secondChar = line.charAt(i + 1);
}
}
}
}
有没有更好的方法来遍历数组/字符串并同时获取偶数和奇数长度字符串/数组的两个元素/字符?,很想了解更多。
答:
0赞
Daksharaj kamal
11/9/2023
#1
您下面的代码片段已经非常合理,我认为没有更好的解决方案,但您可以通过执行以下操作使其看起来更干净 -
public void readTwoChars(BufferedReader b) {
String line = null;
while ((line = b.readLine()) != null) {
int length = line.length();
for (int i = 0; i < length; i += 2) {
char firstChar = line.charAt(i);
char secondChar = (i + 1 < length) ? line.charAt(i + 1) : 0;
}
}
}
0赞
deHaar
11/9/2023
#2
您可以将循环更改为从 开始,只要小于输入的长度(在您的情况下为行),就可以取对:for
i = 1
char
(i - 1, i)
i
String
public void readTwoChars(BufferedReader b) {
String line = null;
while ((line = b.readLine()) != null) {
// start at 1 and use a simple increment
for (int i = 1; i < line.length(); i++) {
// then just take the pair
char firstChar = line.charAt(i - 1);
char secondChar = line.charAt(i);
}
}
}
评论
String
没有迭代器。它不是.您可以编写自己的迭代器,但我认为这太过分了。Iterable
String
i < line.length()-1
if
i = 1
for(int ch: (Iterable<Integer>)() -> string.chars() .iterator()) { … }