【问题标题】:Is there a way that I can set certain parts of a string into an array incrementally? (Java)有没有办法可以将字符串的某些部分增量设置为数组? (爪哇)
【发布时间】:2017-03-16 01:14:10
【问题描述】:

例如, 字符串字母 = "fourgooddogsswam";

有没有一种方法可以一次从左到右扫描字符串 4 个字符,以便我可以将(四个 ourg urgo rgoo good oodd oddo ddog dogs ogss gssw sswa swam)设置为字符串数组? 我尝试使用循环,但很难让它正常工作。

谢谢!

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

【问题讨论】:

  • 向我们展示您的尝试并解释您遇到的问题。
  • 请显示您尝试过的循环。 SO 不是免费的编码服务。
  • 我输入了我正在处理的内容,基本上我引入了一串字母并使用 wordSize int 来确定它为每个单词扫描字符串的字母数。 Fourgooddogsswam 示例使用了 4

标签: java arrays string loops


【解决方案1】:

像这样使用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);

    }

【讨论】:

  • 有没有办法在没有 ArrayLists 的情况下做到这一点?
  • 当试图在方法中使用它时,我返回子字符串,但它给了我这个作为输出:[Ljava.lang.String;@15db9742 而不是数组值。
  • 所以我需要返回一个字符串数组?
  • 无论你需要什么,你想要一个数组吗?好的。你想要一个包含所有子字符串的字符串吗?然后看上面的链接。
【解决方案2】:

这只是另一种方法。

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

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

【讨论】:

    猜你喜欢
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    相关资源
    最近更新 更多