旋转列表<Character>并维护字数
Rotating List <Character> and maintaining word number
我正在尝试将字符串逐行旋转到右侧(来自文件的输入)。输入可能有很多行,因此需要每行进行旋转。
例如,将其向右旋转 5
and line breaks^$@
最终会是:^$@ and line breaks
.
我正在使用 List<String>
并完成了以下工作:
private static List<String> rflag(String value, List<String> lines) {
List<String> newLines = new ArrayList<>();
int rvalue = Integer.parseInt(value);
for (String line : lines) {
StringBuilder sb = new StringBuilder();
if (!line.isEmpty()) {
List <Character> chars= new ArrayList<>();
for(char ch: line.toCharArray()){
chars.add(ch);
}
Collections.rotate(chars, rvalue);
sb.append(chars);
String text = sb.toString()
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.trim();
newLines.equals(text);
}
}
return newLines;
}
如果我输入类似 abcXYZ
的内容,我的输出最终会是 [b, c, X, Y, Z, a]
或 bcXYZa
并删除括号和逗号。
我的主要问题是,虽然我可以删除括号和逗号,但我没有保留输入中的行或词。
改变
.replace(",", "") //remove the commas
到
.replace(", ", "") //remove the commas
使此代码按预期工作。
System.out.println(rflag("2", Arrays.asList("and line breaks"))); //output: ksand line brea
(and line breaks^$@
,目前的输出是 ^ $ @ a n d l i n e b r e a k s
但应该是 ^$@ and line breaks
。)
我正在尝试将字符串逐行旋转到右侧(来自文件的输入)。输入可能有很多行,因此需要每行进行旋转。
例如,将其向右旋转 5
and line breaks^$@
最终会是:^$@ and line breaks
.
我正在使用 List<String>
并完成了以下工作:
private static List<String> rflag(String value, List<String> lines) {
List<String> newLines = new ArrayList<>();
int rvalue = Integer.parseInt(value);
for (String line : lines) {
StringBuilder sb = new StringBuilder();
if (!line.isEmpty()) {
List <Character> chars= new ArrayList<>();
for(char ch: line.toCharArray()){
chars.add(ch);
}
Collections.rotate(chars, rvalue);
sb.append(chars);
String text = sb.toString()
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.trim();
newLines.equals(text);
}
}
return newLines;
}
如果我输入类似 abcXYZ
的内容,我的输出最终会是 [b, c, X, Y, Z, a]
或 bcXYZa
并删除括号和逗号。
我的主要问题是,虽然我可以删除括号和逗号,但我没有保留输入中的行或词。
改变
.replace(",", "") //remove the commas
到
.replace(", ", "") //remove the commas
使此代码按预期工作。
System.out.println(rflag("2", Arrays.asList("and line breaks"))); //output: ksand line brea
(and line breaks^$@
,目前的输出是 ^ $ @ a n d l i n e b r e a k s
但应该是 ^$@ and line breaks
。)