繁体   English   中英

有没有办法可以逐步将字符串的某些部分设置为数组? (JAVA)

[英]Is there a way that I can set certain parts of a string into an array incrementally? (Java)

例如,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;
}

像这样使用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);的字符串数组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);

    }

只是另一种方式来做到这一点。

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));
  }
 }
}

将打印:

four
good
dogs
swam

PS是的,我们都讨厌正则表达式......但它确实有效;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM