Java – how do I ignore spaces in substrings?
I have a text box that makes suggestions based on user input. One of my text boxes is location - based
The problem is that if users type in Chicago, Illinois, everything is normal, but if they type in Chicago, Illinois, the suggestion will stop The only difference between the two is the space after the comma
How can I solve this problem so that even if the user puts 2 or 4 spaces after the comma, it still displays the same result 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've tried this too:
String state = location.substring(location.indexOf(",".trim()) + 1);
String variables are used to call the database; That's why I have to eliminate any spaces
Solution
You can use location replaceAll(“”,“”)
Used to extract the location to the city and state. You can use the split () method as the
String location [] = location. split(“,”);
Now?
String city=location[0]; String state=location[1];
Editor: (for whom)
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);