【问题标题】:How to get some characters in String Android如何在String Android中获取一些字符
【发布时间】:2020-04-12 07:57:40
【问题描述】:

我有一个动态字符串,比如“Longitude (141.35642453456) Latitude (532.892392)”,当位置不同时,经度和纬度可以改变。

我的问题是如何获取经度数并将其设置为字符串经度?以及如何获取纬度数并将其设置为字符串纬度?

【问题讨论】:

  • 您会得到“经度 (141.35642453456) 纬度 (532.892392)”作为响应吗?还是只有数字作为回应?
  • 只有数字经度设置为字符串经度,只有数字纬度设置为字符串纬度@Swapnil

标签: java android string


【解决方案1】:

这是一个简单的解决方案:

    class Scratch {
    public static void main(String[] args) {
        String input = "Longitude (141.35642453456) Latitude (532.892392)";

        String s = input.replaceAll("[^0-9.\\s]", "");
        //  141.35642453456  532.892392
        System.out.println(s);

        String trim = s.trim();
        System.out.println(trim);

        String[] split = trim.split("\\s+");

        String longitude = split[0];
        String latitude = split[1];

        System.out.println(longitude);
        System.out.println(latitude);

    }
}

【讨论】:

    【解决方案2】:

    对于静态使用,您可以简单地使用以下方式获取子字符串:-

        String lonlat = "Longitude (141.35642453456) Latitude (532.892392)";
        String longitude = lonlat.substring(lonlat.indexOf("(") + 1, lonlat.indexOf(")"));
        String latitude = lonlat.substring(lonlat.lastIndexOf("(") + 1, lonlat.lastIndexOf(")"));
    

    或者您可以更动态地执行更多值

        String example = "Longitude (141.35642453456) Latitude (532.892392)";
        Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(example);
        ArrayList<String> latLonng = new ArrayList<>();
        while (m.find()) {
            System.out.println(m.group(1));
            latLonng.add(m.group(1));
        }
        String longitude = latLonng.get(0);
        String latitude = latLonng.get(1);
    

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 2010-10-28
      • 1970-01-01
      相关资源
      最近更新 更多