如何在 Java 中使用循环将字符串分成字母组?

我必须编写一个将字符串分成组的方法。用户应该给出每组字母的数量,函数应该返回一个字符串,该字符串由分成几组的输入字符串组成。例如,function(“HELLOYOU”, 2) 将返回“HE LL OY OU”。



元芳怎么了
浏览 137回答 3
3回答

慕田峪4524236

您可以使用下面的代码,它接受一个String实例和一个int定义要分割的字符数的N。然后使用String实例split方法。public static String[] split(String input, int len){    // To prevent any NullPointerException being thrown    if (StringUtils.isEmpty()) {        return null;    }    // Split the input string based on a regex pattern    return input.split(String.format("(?<=\\G.{%1$d})", len));}这里使用的正则表达式是(?<=\\G.{%1$d})基于lenbeing2的正则表达式(?<=\\G.{2})。所以这意味着它将每 2 个字符拆分一次。因此,字符串的输出HELLOWORLD将为HE, LL, OW, OR, LD。如果您想将它们合并为一个String空间,您可以使用该StringUtils#join方法。String joinedString = StringUtils.join(split, StringUtils.SPACE);哪个会产生"HE LL OW OR LD"。所以一个多合一的方法是:public static String separateNthCharacter(String input, int len) {    // To prevent any NullPointerException being thrown    if (StringUtils.isEmpty()) {        return StringUtils.EMPTY;    }    String[] split = input.split(String.format("(?<=\\G.{%1$d})", len));    return StringUtils.join(split, StringUtils.SPACE);}

qq_花开花谢_0

您可以将输入字符串的字符移动到新字符串,并在等于“大小”的每个步骤上放置空格:String function(String input, int parts) {&nbsp; &nbsp; StringBuilder result = new StringBuilder();&nbsp; &nbsp; int partCounter = 0;&nbsp; &nbsp; for (int i = 0; i < input.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; partCounter++;&nbsp; &nbsp; &nbsp; &nbsp; result.append(input.charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; if (partCounter == parts){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.append(" ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; partCounter = 0;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result.toString();}

一只斗牛犬

您可以使用String.split()将字符串分解为单个字母的数组,然后组合成对的字母或更大的组等。这是一些示例代码:String[] splitInParts(String input, int size) {&nbsp; &nbsp; String[] letters = input.split("");&nbsp; &nbsp; String[] output = new String[letters / size];&nbsp; &nbsp; for (int i = 0; i < output.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; output[i] = "";&nbsp; &nbsp; &nbsp; &nbsp; for (int j = 0; j < size; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output[i] = output[i] + letters[size * i + j];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return output;}缺少很多样板代码,例如,检查循环参数是否在范围内,检查字符串是否为空等。但是,这是您如何着手去做的粗略想法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java