【问题标题】:How can I ignore spaces in a substring?如何忽略子字符串中的空格?
【发布时间】:2015-12-17 17:42:16
【问题描述】:

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

问题是,如果用户输入 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);

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

【问题讨论】:

  • 试试String state = location.substring(location.indexOf(",") + 1).trim();
  • 使用 state.trim() 和 city.trim()

标签: java substring indexof


【解决方案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();
}

【讨论】:

  • “trim”的定义在这里没有价值,因为 OP 对于它的用途有一些的想法。相反,你为什么不解释为什么你把修剪操作放在那里?
  • 非常感谢,它成功了,在外面使用了装饰。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    修剪整个结果。例如:

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

    【讨论】:

      【解决方案4】:

      我该如何解决这个问题,这样即使用户在之后输入 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);
      

      【讨论】:

      • 非常感谢,这是完美的
      • “纽约,纽约”怎么样
      • @Whome 检查编辑。
      【解决方案5】:

      使用

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

      代替

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

      应该可以的。

      【讨论】:

        猜你喜欢
        • 2014-10-22
        • 2015-02-18
        • 2013-11-19
        • 1970-01-01
        • 2014-05-29
        • 2018-12-16
        • 1970-01-01
        • 1970-01-01
        • 2015-09-14
        相关资源
        最近更新 更多