[英]Group string characters into a given length
I have written a simple code that groups a certain string into N length then print it out to the console where the group of characters are divided by "|" 我编写了一个简单的代码,将某个字符串分组为N个长度,然后将其打印到控制台上,在该控制台中,字符组除以“ |” character.
字符。 Is there a simpler way to do this?
有没有更简单的方法可以做到这一点? By the way, this is my code.
顺便说一句,这是我的代码。
String d = "stackoverflow.com";
char[] x = d.toCharArray();
StringBuilder ad = new StringBuilder();
int r = 0;
int f = 6;
/*
f = 1; 2 characters by group
f = 2; 3 characters by group
...
f = n; (n+1) characters by group
*/
for (char a : x) {
if (r == f) {
ad.append(a);
System.out.print(ad+"|");
ad.delete(0, 1);
} else {
ad.append(a);
r++;
}
}
Its output will be (f = 6) 输出为(f = 6)
stackov|tackove|ackover|ckoverf|koverfl|overflo|verflow|erflow.|rflow.c|flow.co|low.com|
If you wrap System.out
in a PrintWriter
, you can use the overload of PrintWriter.write
which prints a portion of the string: 如果将
System.out
包装在PrintWriter
,则可以使用PrintWriter.write
的重载来打印字符串的一部分:
PrintWriter pw = new PrintWriter(System.out, true);
for (int i = 0; i <= d.length() - f; ++i) {
pw.write(d, i, f);
pw.print('|');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.