Sunday, 7 December 2014

WAP to search for a given string in an array of strings.This is achieved by comparing the searching string with each of the array elements one by one in a loop.

//Search.java
import java.io.*;
class  Search
{
public static void main(String[] args) throws Exception
{
//to accept data from key board
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many String ??");
int n=Integer.parseInt(br.readLine());
   
   //create a string type array with size n
String str[]=new String[n];

//store string in to str[]
for(int i=0; i<n; i++)
{
          System.out.println("Enter a string");
str[i]= br.readLine();
}

//accept  the string to search
System.out.println("Enter a string to search");
String search= br.readLine();

//take a boolean var.
boolean found = false;

//search for the string in str[]
for(int i=0; i<n; i++)
{
   if (search.equalsIgnoreCase(str[i]))
  {
              System.out.println("Found at Position : "+(i+1));
found = true; //string found

   }
}
//if not found , display message
if(!found)
System.out.println("Not found in the array");
}
}

No comments:

Post a Comment