[英]How can I split a string into substrings?
我想將字符串"KD-435"
分為兩個子字符串,以檢查第一個子字符串"KD-"
是否以以下字符"KD-"
開頭,第二個子字符串為數字beteewn "400-500"
。
我有以下方法,並且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());
}
}
}
您可以使用正則表達式一次完成所有操作:
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
}
}
您不必顯式地拆分它(就調用String.split
),例如
if (s.startsWith("KD-")) {
int v = Integer.parseString(s.substring(3));
if (v >= 400 && v <= 500) {
// Do whatever.
}
}
您將需要處理s.substring(3)
可能無法解析為整數的事實。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.