
How to search a string in given String array?

import java.util.Scanner;
public class StringSearch {
public static void main(String[] args) {
String city[] = { "Delhi", "Lucknow", "Mumbai", "Kanpur" };
String userCity;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter city name you want to search in list: ");
userCity = scanner.next();
int i = 0;
int flag = 0;
while (i < city.length) {
if (userCity.equalsIgnoreCase(city[i])) {
flag = 1;
break;
} else {
flag = 0;
i++;
}
}
if (flag == 1) {
System.out.println("City found");
} else {
System.out.println("Try another city");
}
}
}
Description: We have taken a String array of city.User will input its city and for searching we used userCity.equalsIgnoreCase(city[i])). EqualsIgnoreCase() method is used to search without caring of case. you can also use equals() method if string case is considered.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.