循环遍历数组内的数组

时间:2013-12-08 04:55:36

标签: java for-loop nested-loops

我有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 个答案:

答案 0 :(得分:0)

我将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.

答案 1 :(得分:0)

最简洁的方法是用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的格式(?<=[XZ])与分隔符XZ匹配,但will not consume the delimiters匹配。例如:

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

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