For example, String letters = "fourgooddogsswam";
Is there a way I can scan the string from left to right 4 characters at a time so that I can set(four ourg urgo rgoo good oodd oddo ddog dogs ogss gssw sswa swam) into a string array? I tried using loops but I'm having difficulties getting it to work properly.
Thanks!
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;
}
Use a while loop and arraylist like this,
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);
}
If you want to do this without arraylist just make a string array with size YOURSTRING.length() - (WHATEVERSIZE - 1);
Example
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);
}
Just another way to do this.
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));
}
}
}
Will print:
four
good
dogs
swam
PS Yes, we all hate regex... but it does the work ;)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.