例如, String letters =“fourgooddogsswam”;
有没有办法我可以一次从左到右扫描4个字符的字符串,以便我可以设置(字符串数组中的四个字符组合?) 我尝试使用循环,但我很难让它正常工作。
谢谢!
public static String[] findWordsOfLength(String letters, int wordSize) {
if(letters == null) {
return null;
}
int size = letters.length();
int wordMax = size - wordSize + 1;
if(size < wordMax || wordMax <= 0) {
return new String[0];
}
int j = 0;
String[] result = new String[wordMax];
for (int i = 0; i < wordMax; i++) {
result[j ++] = letters.substring(i, i + wordSize);
}
return result;
}
答案 0 :(得分:2)
像这样使用while循环和arraylist,
String hello = "fourgooddogsswam";
List<String> substrings = new ArrayList<>();
int i = 0;
while (i + 4 <= hello.length()) {
substrings.add(hello.substring(i, i + 4));
i++;
}
for (String s : substrings) {
System.out.println(s);
}
如果你想在没有arraylist的情况下这样做,只需创建一个大小为YOURSTRING.length() - (WHATEVERSIZE - 1);
的字符串数组
实施例
String hello = "fourgooddogsswam";
String[] substrings = new String[hello.length() - 3];
int i = 0;
while (i + 4 <= hello.length()) {
substrings[i] = hello.substring(i, i + 4);
i++;
}
for (String s : substrings) {
System.out.println(s);
}
答案 1 :(得分:1)
这是另一种方法。
origin/HEAD
将打印:
import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Test {
public static void main(String args[]) {
String str = new String("fourgooddogsswam");
Pattern pattern = Pattern.compile(".{4,4}");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(0));
}
}
}
P.S。 是的,我们都讨厌正则表达式......但它确实有效;)