Ankit Kumar
Ankit Kumar

Reputation: 3723

using java select city and country from a given string that contains full address

I am writing a code in which I want user to provide a string of unknown length.. suppose he provided a string.. now I want to get city and country present in that string... If anybody have any better idea, please share..

Upvotes: 0

Views: 3367

Answers (3)

Gautam
Gautam

Reputation: 238

Well, your questions are very interesting. The program you are writing now is depending on LOGIC and I think there is no such jar files available to get solution on it. It is better to get solution manually. Did you ever think about Dictionary program. Mostly Dictionary words are written in a text file and at run time, the program load that words into an array or some other Collections. This way you can also Load Your file at runtime into a 2D array or collection(mostly HashMap is used). So you can scan your file and load it.Suppose u want to read Example:

Agra,India

London,England

Yangon,Myanmar

Tokyo,Japan

etc...

` String line;

FileInputStream fstream = new FileInputStream(dataFile);

//dataFile is your file directory

DataInputStream in = new DataInputStream(fstream);

BufferedReader br = new BufferedReader(new InputStreamReader(in)); 

HashMap<String,String> divideCityCountry =new HashMap<String,String>();

while((line=br.readLine())!=-1)

{

String[] lineSplit = line.split(",");//use the ',' as delimiter 

divideCityCountry.put(lineSplit[0], lineSplit[1]);

} ` 

Now you can check or get the city and country in the divideCityCountry HashMap(). Hope this may helpful.Good Luck!

Upvotes: 0

codewiz
codewiz

Reputation: 196

In the question you never specified the format of the input string but assuming the format is "city, country" then this works

String s = "the name of a city, the name of a country";
String city = s.substring(0, s.indexOf(", "));
String country = s.substring(s.indexOf(", ") + 2);
System.out.println("City = " + city);
System.out.println("Country = " + country);

Upvotes: 0

Gautam
Gautam

Reputation: 238

As your requirement, you have to build a case where you need to defined all the possibility city or country like Array city= new Array["America","England","China","Myanmar"]; after that now loop your array then read the user defined line from index 0 and each time move your character point +1(do in a loop too)(convert it in String) then search your city pattern to match with the character(String). Your program complexity will increase more and more due to your requirement, I think your complexity will raise up to O(n*n), it is not good for memory. On my view of point, you should ask from user to get the actual requirement step by step like (Enter City :_ then Enter Country :__) it is better to handle the string.GOOD LUCK!

Upvotes: 1

Related Questions