範圍在字符串中的字符,我對如何制定出一個字符串包含在一組順序字符的範圍有點卡住了。 (真/假)確認有爲了
EG。 abc1deeef2hh hijk3lmno
所以我需要檢查,如果這個字符串包含一個1,2,3設置的順序。所以3不能來任何建議,將理解的前2或1等
。
範圍在字符串中的字符,我對如何制定出一個字符串包含在一組順序字符的範圍有點卡住了。 (真/假)確認有爲了
EG。 abc1deeef2hh hijk3lmno
所以我需要檢查,如果這個字符串包含一個1,2,3設置的順序。所以3不能來任何建議,將理解的前2或1等
。
我會採取這裏的方法是刪除所有非數字字符,然後簡單地做一個單程下來的字符串,檢查,以確保沒有後續數小於之前什麼來。
public static boolean isInOrder(String input) {
if (input == null || input.length() == 0) {
return true;
}
String inputNums = input.replaceAll("[^\\d]", "");
char prev = inputNums.charAt(0);
for (int i=1; i < inputNums.length(); ++i) {
char curr = inputNums.charAt(i);
if (curr < prev) {
return false;
}
prev = curr;
}
return true;
}
public static void main(String[] args) {
String input = "abc1deeef2hh hijk3lmno";
System.out.println(input + ", " + isInOrder(input));
input = "abc2deeef1hh hijk3lmno";
System.out.println(input + ", " + isInOrder(input));
}
輸出:
abc1deeef2hh hijk3lmno, true
abc2deeef1hh hijk3lmno, false
演示在這裏:
你可以用JS做的一樣好
function checkOrderedArrElm(array, order) {
var m = 0;//Counter
var current_num;
var next_num;
var result = array;
var test;
if (array !== undefined) {
if (array.constructor === Array) {
result = true;
while (m < array.length) {
current_num = array[m];
next_num = array[m + 1];
if (typeof current_num === "number" &&
typeof next_num === "number") {
if (order) {
test = current_num >= next_num;
} else {
test = current_num <= next_num;
}
if (test) {
result = false;
break;
}
}
m += 1;
}
}
}
return result;
}
var strInput= "abc1deeef2hhh ijk3lmno";
function ExtractNumberFromString(strInput) {
var indices = [];
var inputVal = strInput;
console.log(inputVal);
for (var i = 0; i < inputVal.length; i++) {
if (Number(inputVal[i])) indices.push(Number(inputVal[i]));
}
return indices;
}
checkOrderedArrElm(ExtractNumberFromString(strInput), true));
您可以點擊這裏https://www.w3schools.com/code/tryit.asp?filename=FEYURSRVZMXH