Sunday, June 26, 2022
HomeSoftware DevelopmentDiscover and return index of given String in a Multidimensional Array

Discover and return index of given String in a Multidimensional Array


  

public class Main {

    

    public static int[] findIndex(String stringArr[][],

                                  String keyString)

    {

        

        

        int result[] = { -1, -1 };

        

        

        for (int i = 0; i < stringArr.length; i++) {

            

            for (int j = 0; j < stringArr[i].length; j++) {

                

                if (stringArr[i][j].equals(keyString)) {

                    result[0] = i;

                    result[1] = j;

                    return result;

                }

            }

        }

        

        return result;

    }

  

    

    public static void main(String args[])

    {

        

        String[][] stringArr = { { "a", "h", "b" },

                                 { "c", "d", "e" },

                                 { "g", "t", "r" } };

        

        String keyString = "e";

        

        

        int[] result = findIndex(stringArr, keyString);

        

        System.out.print("The indices are:- ");

        for (int i = 0; i < result.length; i++) {

            System.out.print(result[i] + " ");

        }

    }

}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments