如何忽略子字符串中的空格?

时间:2015-09-21 05:52:11

标签: java substring indexof

我有一个文本框,根据用户输入提供建议,我的一个文本框是基于位置的。

问题是,如果用户输入 Chicago,IL ,一切正常,但如果他们输入 Chicago,IL ,建议就会停止。两者之间的唯一区别是逗号后面的空格。

如何解决此问题,以便即使用户在逗号后放入2或4个空格,它仍会显示与第一种情况相同的结果?

这是我的代码:

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 ?";

  }

我也试过这个:

 String state = location.substring(location.indexOf(",".trim()) + 1);

字符串变量用于调用数据库;这就是我必须消除任何空格的原因。

5 个答案:

答案 0 :(得分:3)

  

我该如何解决这个问题,以便即使用户放入2或4个空格   逗号它仍然显示与第一种情况相同的结果?

您可以使用location.replaceAll(" ", "")

用于将位置提取到city,state 您可以使用split()方法

String location[]=location.split(",");

现在

    String city=location[0];
    String state=location[1];

编辑:(对于谁)

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);

答案 1 :(得分:2)

你使用trim()是正确的方向。但是,你把它放在了错误的地方 ",".trim()始终会产生","。你想修剪子串操作的结果:

String state = location.substring(location.indexOf(",") + 1).trim();

答案 2 :(得分:1)

尝试在正确的位置使用java.lang.String trim()功能。

",".trim()上的

将产生","

需要trim()最终结果。

if (location.contains(",")) {
String city = location.substring(0, location.indexOf(",")).trim();
String state = location.substring(location.indexOf(",")).trim();
}

答案 3 :(得分:1)

修剪整个结果。例如:

String city = (location.substring(0, location.indexOf(","))).trim();
String state = (location.substring(location.indexOf(",") + 1)).trim();

答案 4 :(得分:0)

使用

String state = location.substring(location.indexOf(",") + 1).trim();

而不是

String state = location.substring(location.indexOf(",".trim()) + 1);

这应该有效。

相关问题