简体   繁体   English

将字符串字符分组为给定长度

[英]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.

相关问题 获取任何给定输入字符串中带有不同字符的最长子字符串的长度 - Get the length of longest substring with distinct characters in any given input string 给定一个字符串,生成所有 2 个连续的字符、3 个连续的字符……等等直到 ( str.length()-1 ) 个连续的字符 - Given a string, generate all 2-consecutive characters, 3-consecutive characters…and so on up to ( str.length()-1 )-consecutive characters 包含代理字符的字符串的长度-Java - length of a String with surrogate characters in it - java 给定字符串长度,如何将输入作为字符串 - How to take input as String given the String Length Java 滑动窗口问题:给定一个字符串,找出最长的子字符串的长度,它包含所有不同的字符。 比较解决方案 - Java Sliding Window Problem: Given a string, find the length of the longest substring, which has all distinct characters. Comparing Solutions 给定字节数的最大字符串长度 - Maximum string length for given number of bytes 生成ArrayList的所有排列 <String> 给定长度的 - Generate all permutations of ArrayList<String> of a given length 如何确保加密长度与给定的字符串相同 - How to ensure the encrypted length are same as the given string 给定一个字符串列表,创建一个具有长度和字符串的哈希表 - Given a list of strings, create a hashmap with length and string 从给定长度生成所有可能的字符串 - Generate all possible string from a given length
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM