简体   繁体   中英

How can I split a string into substrings?

I want to split the string "KD-435" into two substrings to check whether the first substring "KD-" begins with the following characters "KD-" and the second substring is number beteewn "400-500" .

I have the following method and I want to change it to do that at this position if (ssid.startsWith("KD-"))

private void check_wifi_available() {
    WifiManager wifiManager = (WifiManager) this
            .getSystemService(this.WIFI_SERVICE);

    final List<ScanResult> results = wifiManager.getScanResults();
    if (results != null) {

        List<ScanResult> updatedResults = new ArrayList<ScanResult>();
        // pick wifi access ponits which begins with these "KD" characters.
        for (int i = 0; i < results.size(); i++) {
            String ssid = results.get(i).SSID;
            if (ssid.startsWith("KD")) {

                updatedResults.add(results.get(i));
            }
        }
        if (updatedResults.size() > 0) {
            String a = calculateBestAccessPoint(updatedResults);
            textWifi.setText(a.toString());
        }
    }
}

You could use a regex to do it all in one fell swoop:

Pattern p = Pattern.compile("^KD-(4[0-9]{2}|500)$");
Matcher m = p.matcher("KD-411"); // Replace with your string.
if (m.matches()) {
    // It worked!
} else {
    // It didn't.
}
    String [] parts = ssid.split("-");

if(parts.length == 2)
{

    String firstPart = parts[0]; //That's KD
    String secondPart = parts[1]; //That's 435

    if(firstPart.equals("KD")&&Integer.parseInt(secondPart)>=400&&Integer.parseInt(secondPart)<=500)
    {
    //do whatever you want
    }
}

You don't necessarily need to explicitly split it (in the sense of invoking String.split ), eg

if (s.startsWith("KD-")) {
  int v = Integer.parseString(s.substring(3));
  if (v >= 400 && v <= 500) {
    // Do whatever.
  }
}

You would need to handle the fact that s.substring(3) might not be parseable as an integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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