I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in Chicago,IL , everything works, but if they type in Chicago, IL , the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
I have also tried this:
String state = location.substring(location.indexOf(",".trim()) + 1);
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
you can use location.replaceAll(" ", "")
for extracting the location into city,state
you can use split()
method as
String location[]=location.split(",");
Now
String city=location[0];
String state=location[1];
EDIT:(for Whome)
String location="New York, NY";
String loc[]=location.split(",");
String city=loc[0].trim();
String state=loc[1].trim();
System.out.println("City->"+city+"\nState->"+state);
you were in the right direction by using trim(). However, you put it in the wrong place.
",".trim()
will always yield ","
. you want to trim the result of the substring operation:
String state = location.substring(location.indexOf(",") + 1).trim();
try using java.lang.String
trim() function in the correct place.
trim on ",".trim()
will produce ","
.
Need to trim()
the final result.
if (location.contains(",")) {
String city = location.substring(0, location.indexOf(",")).trim();
String state = location.substring(location.indexOf(",")).trim();
}
Trim the entire result. For example:
String city = (location.substring(0, location.indexOf(","))).trim();
String state = (location.substring(location.indexOf(",") + 1)).trim();
Use
String state = location.substring(location.indexOf(",") + 1).trim();
Instead of
String state = location.substring(location.indexOf(",".trim()) + 1);
That should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.