简体   繁体   English

Java在char [] []数组中搜索字符串

[英]Java searching for a string in char[][] array

I'm trying to search for a string in a char[][] array. 我正在尝试在char [] []数组中搜索字符串。

I think the problem with my code is that when charArray[k] is found to be a match, charArray[k+1] needs to match puzzle[i][j+1] and continues to match for the entire charArray.length. 我认为我的代码存在的问题是,当发现charArray [k]是一个匹配项时,charArray [k + 1]需要匹配Puzzle [i] [j + 1],并在整个charArray.length上继续匹配。

But because the length of the given word is not predetermined, i can't write super complicated multiple nested for loops for each value of the word. 但是因为给定单词的长度不是预先确定的,所以我无法为单词的每个值编写超复杂的多重嵌套for循环。

also, when my code finds charArray[k], firstly it doesn't increase the value of k, also it doesn't begin the search of next character from where it left off. 同样,当我的代码找到charArray [k]时,首先它不会增加k的值,也不会从中断处开始搜索下一个字符。

I feel like the solution might be with having two methods exchange information between? 我觉得解决方案可能是两种方法之间交换信息? or a recursive method nested within the first for loop somehow? 还是以某种方式嵌套在第一个for循环中的递归方法?

please help! 请帮忙!

thank you! 谢谢!

public static Boolean search(char[][] puzzle, String word) {

    char[] charArray = word.toCharArray();

    //search array

    for(int k = 0; k < charArray.length; k ++) {

        for (int i = 0; i < puzzle.length; i++) {
            for(int j = 0; j < puzzle[i].length; j++) {
                if ( puzzle[i][j] == charArray[k])
                    continue;

            }
        }
    }
    return true;

}

If you only have horizontal words then this code will do: 如果只有水平词,则此代码将执行以下操作:

public class Test {

    private static char[][] puzzle = {
            { 'a' ,'z', 'e'},
            { 'a' ,'z', 'f','g'},
            { 'a' ,'z', 't', 'k','m'},
            { 'a' ,'z', 'k'}
    };

    public static void main(String[] args) {
        System.out.println(search(puzzle, "azh"));
        System.out.println(search(puzzle, "azgg"));
        System.out.println(search(puzzle, "azfg"));
        System.out.println(search(puzzle, "aztkm"));
    }

    public static Boolean search(char[][] puzzle, String word) {
        for (int i = 0; i < puzzle.length; i++) {
            String puzzleWord = new String(puzzle[i]);
            if (word.equals(puzzleWord)) {
                return true;
            }
        }
        return false;
    }
}

Do you also need to check for vertical words? 您还需要检查垂直单词吗?

There is two thing at code. 代码有两件事。

  • First is that why do you continue because you found a equality, you should iterate on array.(when you do continue, iteration exit loop. " if ( puzzle[i][j] == charArray[k])" 首先是为什么要继续,因为找到相等,所以应该在数组上进行迭代。(当继续时,迭代退出循环。“ if(puzzle [i] [j] == charArray [k])”

  • The second thing is you are not increase 'k' index. 第二件事是您没有增加'k'指数。 In order to make a right comparison, you should increase two index. 为了进行正确的比较,您应该增加两个索引。 ( if ( puzzle[i][j] == charArray[k++])). (if(puzzle [i] [j] == charArray [k ++]))。

Please try this code. 请尝试此代码。 You don't need outer loop ."for(int k = 0; k < charArray.length; k ++) {" . 您不需要外部循环。“ for(int k = 0; k <charArray.length; k ++){”。

public static void main(String[] args) {
    //Found case
    char[][] puzzle = {{'b','o','o','k'}, {'a','p','p','l','e'}, {'t','a','b','l','e'}};
    String word = "apple";
    System.out.println("result: " + search(puzzle, word));
    //Output is-> result: true

    //Not Found case
    char[][] puzzle2 = {{'b','o','o','k'}, {'a','p','p','l','e','e'}, {'t','a','b','l','e'}};

    System.out.println("result: " + search(puzzle2, word));
    //Output is-> result: false
}

public static Boolean search(char[][] puzzle, String word) {

    char[] charArray = word.toCharArray();

    //search array

    for (int i = 0; i < puzzle.length; i++) {
        for(int j = 0; j < puzzle[i].length && j < charArray.length; j++) {
            //when not equal character or lengths are not equal break loop
            if ( puzzle[i][j] != charArray[j] || puzzle[i].length != charArray.length)
                break;
            //Equal and all characters compared
            else if( j + 1 == puzzle[i].length){
                return true;
            }

        }
    }
    return false;

}

Let be quick and dirty using Stream : 让我们快速而肮脏地使用Stream

First, iterate the array : 首先,迭代数组:

Arrays.stream(array)

Then, search for any matched using Arrays.equals , you will need to get the char[] of your String 然后,使用Arrays.equals搜索任何匹配项,您将需要获取Stringchar[]

char[] search = word.toCharArray();

Let use anyMatch to tell us if there is at least one match in that Stream : 让我们使用anyMatch告诉我们该Stream是否至少有一个匹配项:

.anyMatch(a -> Arrays.equals(a, search));

The Predicate used here simply use Arrays.equals to will check if both char[] are the sames. 这里使用的Predicate仅使用Arrays.equals来检查两个char[]是否相同。 This is simple and doesn't required to instantiate String . 这很简单,不需要实例化String

Full code : 完整代码:

public static boolean search(char[][] array, String word){
    char search = word.toCharArray();
    return Arrays.stream(array)
                 .anyMatch(a -> Arrays.equals(a, search));
}

Your solution 您的解决方案

First, you don't want to iterate the word to find but the char[][] directly. 首先,您不需要迭代单词来查找,而是直接使用char[][]进行迭代。 For each row, you will iterate the charArray . 对于每一行,您将迭代charArray

for (int i = 0; i < puzzle.length; i++) {
    //If both length don't match, this can't be good.
    if(puzzle[i].length == charArray.length){
        //Check both array char by char 
        for(int k = 0; k < charArray.length; k++) {
            if (puzzle[i][j] != charArray[k])
                break; //doesn't match, skip that row
            }

            if (charArray.length - 1 == k){ return true; }
        }
    }
}
//No match found
return false;

The exit condition could probably be improved but I don't want to take too much time on that part since the comparison could be done simply using Arrays.equals : 退出条件可能会得到改善,但是我不想在那部分花费太多时间,因为可以使用Arrays.equals进行比较:

for (int i = 0; i < puzzle.length; i++) {
    if(Arrays.equals(puzzle[i], charArray)
        return true;
}
//No match found
return false;

All the answers here match if a String from String array matches a given value but I don't think that's what are you looking for :/ I've made a custom method that matches for a particular word is part of the char[][] array. 如果String数组中的String匹配给定值,则此处的所有答案均匹配,但我认为这不是您要查找的内容:/我已经为特定单词匹配的自定义方法是char [] [的一部分] ]数组。

public static Boolean wordExistsInCharArray(char[][] puzzle, String word) {

    char[] charArray = word.toCharArray();

    //search array for words only! A word is defined when there is a whitespace on both sides or start/end of input.

    int currentWordIndex, charArrayIndex;

    for (int i = 0; i < puzzle.length; i++) {
        currentWordIndex = 0;
        charArrayIndex = 0;
        for (int j = 0; j < puzzle[i].length; j++) {
            if (puzzle[i][j] == ' ') { //word has ended and we need to check if it matches the one we are looking for.
                currentWordIndex = 0;
                if (charArrayIndex == charArray.length) {
                    return true; // all the characters in the word were presented in current puzzle row. You now have both i, j indexes.
                }
                charArrayIndex = 0;
            } else {
                currentWordIndex++; // extend current word length with one character
                if (currentWordIndex - 1 == charArrayIndex) { // check if current word length and parsed characters length are equal otherwise just continue
                    if (charArrayIndex < charArray.length && charArray[charArrayIndex] == puzzle[i][j]) { // test if next character from charArray matches current word character
                        charArrayIndex++; // extend charArrayIndex if there is a match
                    } else {
                        charArrayIndex = 0; // reset charArrayIndex since there is no match or current word length is bigger than needed.
                    }
                } else {
                    continue;
                }
            }
        }
        if (charArrayIndex == charArray.length) { // in the case when the puzzle[i] has ended and we did not check if we have any occurrence
            return true; // all the characters in the word were presented in current puzzle row. You now have both i, j indexes.
        }
    }
    return false;
}

and then for the tests like: 然后进行如下测试:

    char[][] puzzle1 = new char[][] {
            {'f', 'o', 'o', ' ', 'b', 'a', 'r'},
            {'f', 'o', 'o', ' ', 'b', 'u', 'z'},
            {'f', 'o', 'o', ' ', 'f', 'i', 'g', 'h', 't', 'e', 'r'}
    };

    char[][] puzzle2 = new char[][]{
            {'f', 'o', 'o', ' ', 'b', 'a', 'r'},
            {'f', 'o', 'o', ' ', 'b', 'u', 'z'},
            {'f', 'o', 'o', ' ', 'f', 'i', 'g', 'h', 't', 'e', 'r', 'e', 'u', 'r', 'o'}
    };

    char[][] puzzle3 = new char[][] {
            {'f', 'o', 'o', ' ', 'b', 'a', 'r'},
            {'f', 'o', 'o', ' ', 'b', 'u', 'z'},
            {'f', 'o', 'o', ' ', 'e', 'u', 'r', 'o', 'f', 'i', 'g', 'h', 't', 'e', 'r'}
    };

    char[][] puzzle4 = new char[][] {
            {'m', 'o', 't', 'h', ' ', 'i', 's', ' ', 'n', 'o', 't', ' ', 'a', ' ', 'r', 'e', 'a', 'l', ' ', 'w', 'o', 'r', 'd'}
    };

    char[][] puzzle5 = new char[][] {
            {'I', ' ', 'l', 'o', 'v', 'e', ' ', 'm', 'y', ' ', 'm', 'o', 't', 'h', 'e', 'r', ' ', 'f', 'o', 'r', ' ', 'r', 'e', 'a', 'l'}
    };

    System.out.println(wordExistsInCharArray(puzzle1, "fighter"));
    System.out.println(wordExistsInCharArray(puzzle2, "fighter"));
    System.out.println(wordExistsInCharArray(puzzle3, "fighter"));

    System.out.println(wordExistsInCharArray(puzzle4, "moth"));
    System.out.println(wordExistsInCharArray(puzzle5, "moth"));

output will be: 输出将是:

true
false
false
true
false

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

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