繁体   English   中英

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

[英]How can I ignore spaces in a substring?

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

问题是,如果用户在伊利诺伊州的 芝加哥打字,一切正常,但如果他们输入伊利诺伊州的芝加哥,建议就会停止。 两者之间的唯一区别是逗号后面的空格。

我该如何解决这个问题,以便即使用户在逗号后放入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);

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

我该如何解决这个问题,以便即使用户在逗号后放入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);

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

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

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

修剪",".trim()将产生","

需要trim()最终结果。

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

修剪整个结果。 例如:

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

使用

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

代替

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

这应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM