Search a string in Matrix Using Split function in Java


To search a string in Matrix using split function, the code is as follows −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static int search_string(String[] my_matrix, String search_string){
      for (String input : my_matrix){
         String[] my_value = input.split(search_string);
         if (my_value.length >= 2 || my_value.length == 0){
            return 1;
         }
         else if (my_value.length == 1 && input.length() != my_value[0].length()){
            return 1;
         }
      }
      return 0;
   }
   public static String[] vertical_search(String[] my_matrix){
      String[] vertical_search_value = new String[my_matrix[0].length()];
      for (int i = 0; i < my_matrix[0].length(); i++){
         String temp = "";
         for (int j = 0; j < my_matrix.length; j++)
            temp += my_matrix[j].charAt(i);
         vertical_search_value[i] = temp;
      }
      return vertical_search_value;
   }
   public static void main(String[] args){
      String[] my_matrix = { "This", "Sample", "This" };
      String search_string = "This";
      String[] vertical_matrix = vertical_search(my_matrix);
      int horizontal_search_result = search_string(my_matrix, search_string);
      int vertical_search_result = search_string(vertical_matrix, search_string);
      if (horizontal_search_result == 1 || vertical_search_result == 1)
         System.out.println("The string has been found in the matrix");
      else
         System.out.println("The string couldn't be found in the matrix");
   }
}

Output

The string has been found in the matrix

A class named Demo defines a function named ‘search_String’ that splits the string and checks to see the length of the string. If the entire row is occupied by the string, the function returns array that has length of 0.

If the string we are looking for is present in between the characters of the string, the length of the array will be greater than 1. The length of the array could be 1 if:

  • The search string occurs in the first half of the array.
  • The search string occurs in the last half of the array.
  • The search string is not present in the array.

Another function named ‘vertical_search’ checks for the search string vertically in the matrix. To search for the string in the columns of the matrix, the matrix is transposed and searched again.

Updated on: 13-Jul-2020

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements