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

How can I ignore spaces in a substring?

我有一个文本框可以根据用户输入给出建议,而我的其中一个文本框是基于位置的。

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

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

这是我的代码:

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

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

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

trim 在 ",".trim() 上将产生 ",".

需要trim()最终结果。

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

您使用 trim() 的方向是正确的。但是,你放错地方了。
",".trim() 将始终产生 ","。你想要 trim 子字符串操作的结果:

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

Trim 整个结果。例如:

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

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?

你可以使用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);

使用

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

而不是

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

应该可以。