Tuesday 20 January 2015

Search a Word in String Array ?

Advertisement


Requirement is to search a particular String in the Array of String value. To achieve this we need to have some set string values in a String array and secondly we need to have a String value to be searched.

Tips to Proceed...

1. Take counter
2. Iterate String and match the value on each iteration using equals() method.

Steps to do....

1. Take a counter count=0 .
2. Get the String to be searched.
3. Iterate the String Array and keep on searching from index=0 till length.
4. While looping keep on matching the string value with each index value of the Array.
5. If it get matched print "Match Found" and increment a counter.
6. If not matched then Print " No Match Found ".

Program :


public class Lab1{

public static void main(String args[]){

int count=0;

String arr[]= new String[10];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String ");

for(int i=0;i<10;i++){ // Iterate loop to store value in Array
System.out.print((i+1)+". ");
arr[i]=sc.next();
}

System.out.println("Enter the String to be searched");
String s=sc.next(); // Enter value to be searched

for(int i=0;i<arr.length;i++){ // Loop to search the Element
if(s.equals(arr[i])){
System.out.println("Match Found");
count++;
}
}

if(count==0) // Checking No Such Element Present in Array
System.out.println("No Element Found ");

System.out.println("No of Words Found in Number:"+count);

}
}










EmoticonEmoticon