【问题标题】:Loop through array inside array循环遍历数组内的数组
【发布时间】:2013-12-08 04:55:35
【问题描述】:

我有 2 个数组:一个包含单词 (words_array),另一个包含字母 (letters_array)

我循环遍历 words_array 并在循环内循环遍历字母数组 在第二个循环中,我做了一个条件“如果单词在字母数组中包含一个字母,则将它除以某种方式,否则它应该按原样打印单词” 但它不起作用,因为它会打印重复的单词。

这是我的代码:

for (int i = 0; i < words_array.length; i++) {
    for (int j = 0; j < letters_array.length ;j++ ) {
        if (arryWords[i].contains(letters[j]+"")) {
            int wordLength = arryWords[i].length();
            int letterIndex = arryWords[i].indexOf(letters[j]);
            String sub = arryWords[i].substring(0, letterIndex + 1);
            System.out.println(sub);
            System.out.println(arryWords[i].substring(letterIndex + 1, wordLength));
        } else if (!arryWords[i].contains(letters[j] + "")) {
            System.out.println(arryWords[j]);
        }
    } 
}

但实际结果是:

hello
hello
hello
he
llo

我想,如果这个词在letters_array中没有任何字母,它只打印一次,如果这个词在letters_array中有一个字母,它应该在创建的位置分成两个2部分我在代码中写的字母。

谢谢。

【问题讨论】:

  • 如果您告诉我们预期结果与实际结果有何不同,将会有所帮助。

标签: java for-loop nested-loops


【解决方案1】:

我将 letters_array 重命名为 lettersArr 并将 words_array 重命名为 wordsArr 但我相信您想要一个 Set 的字符串;例如,

// TreeSet would be ordered.
Set<String> wordSet = new HashSet<String>(); // The set of words.
for (int i = 0; i < wordsArr.length; i++) {
  final String word = wordsArr[i]; // local copy of the word.
  for (int j = 0; j < lettersArr.length; j++) {
    int pos = word.indexOf(lettersArr[j]); // get the position of the letter.
    if (pos > -1) { // if the word contains the letter.
      final String first = word.substring(0, pos)
          .trim();
      final String second = word.substring(
          pos + 1, word.length()).trim();
      if (first.length() > 0) {
        wordSet.add(first); // add before the letter.
      }
      if (second.length() > 0) {
        wordSet.add(second); // add after the letter.
      }
    } else {
      wordSet.add(word); // add the word.
    }
  }
}
System.out.println(wordSet); // display the result.

【讨论】:

  • 感谢您的帮助,但您的代码出现了同样的问题,即再次打印单词直到除以它。正如我在第一篇文章中展示的那样
【解决方案2】:

最简洁的方法是用Regex分割字符串:

public static void main(String... args){
    String[] word_array = {"blahXblahX", "blahYblahY", "blahZblahZ"};
    char[] letters_array = {'X','Z'};

    String pattern = "(?<=[" + new String(letters_array) + "])";
    for(int i=0; i<word_array.length; i++)
        for(String str: word_array[i].split(pattern))
            System.out.println(str);
}

输出:

blahX
blahX
blahYblahY
blahZ
blahZ

解释:

对于此示例,pattern 将具有 (?&lt;=[XZ]) 的形式,它匹配分隔符 XZwill not consume the delimiters。例如:

// consumes delimiter: ["blah","blah"]
"blahXblahX".split("[XZ]");

// keeps delimiter: ["blahX","blahX"]
"blahXblahX".split("(?<=[XZ])");

【讨论】:

  • 感谢您的帮助,但我不喜欢在我的代码中使用正则表达式,我无法按我的意愿处理它
  • 你的意思是上面的代码没有做你想做的事吗?或者您不知道(也不想学习)正则表达式?
  • 没有朋友,它对我有帮助,但它解决了我的一小部分问题,我无法对其进行编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多