Reputation: 6901
I am having 2 Textbox in my application. 1 for Source address and another for Destination Address. Both are AutoComplete textbox and I am getting Data from Google Maps API.
Source Address == SHAHIBAUGUNDERBRIDGE,Shahibagh,Ahmedabad,Gujarat
Destination Address == CGRoad,ShreyasColony,Navrangpura,Ahmedabad,Gujarat
Now what i want is to find the City Name which user has enter from the string. I tried different ways but as we can see that format of Address String is not fixed I am not able to get the City Name. I figure out one thing which is common to get city name is that it will always before the last ",". As you can see that City name -> Ahmedabad in both the String is before the last (COMMA)",". But still I am struggling to get the City Name. If any one has any idea please kindly help me.
Upvotes: 1
Views: 1454
Reputation: 3096
it looks like google is saving the address as:
[roads], [name of location], [city], [state].
Assuming you are correct then that the city is always before the last "," then you could use the split() method on the string.
split takes in a regex (as a string) to use to split up the string in question. However it seems you just want to split on ","
So if you called:
String [] data = myAddress.split(","); // assuming "myAddress" has the Google data
Then you now have in data an array of strings. one element for each section between a ",".
If you wanted to access the next-to-last element of that array it would simply be:
String cityName = data[data.length-2]; // get the 2ed to last element
Now remember, "split()" takes a regex, so be aware of the string you pass it.
Upvotes: 0
Reputation: 2443
If it always the second to last then try
String [] vals = source_address.split(",");
String city = vals[vals.length - 2];
Upvotes: 2