我想要字串中的數字和字母之間的空格。示例:字串 = "KL11AB2432"; 到字串 = “KL 11 AB 2432”;
uj5u.com熱心網友回復:
你們都太辛苦了。達到一個正則運算式!
void main(List<String> arguments) {
const data = "KL11AB2432";
print(insertSpaces(data));
}
String insertSpaces(String input) {
final reg = RegExp(r"([A-Z] |\d )");
final pieces = reg.allMatches(input);
return pieces.map((e) => e.group(0)).join(" ");
}
uj5u.com熱心網友回復:
String str = "KL11AB2432";
List<Object> newList = [];
List<String> strList = str.split("").toList();
for (var i = 0; i < strList.length; i ) {
if (int.tryParse(strList[i]) != null) {
if ((i - 1) >= 0 && int.tryParse(strList[i - 1]) == null) {
newList.add(" ");
newList.add(strList[i]);
} else {
newList.add(strList[i]);
}
} else {
if ((i - 1) >= 0 && int.tryParse(strList[i - 1]) != null) {
newList.add(" ");
newList.add(strList[i]);
} else {
newList.add(strList[i]);
}
}
}
print(newList);
print(newList.join().toString());
結果 =>
[K, L, , 1, 1, , A, B, , 2, 4, 3, 2]
KL 11 AB 2432
uj5u.com熱心網友回復:
我正在使用 try catch 來檢查 int 型別,
bool isInt(String data) {
try {
int.parse(data);
return true;
} catch (_) {
return false;
}
}
void main() {
String data = "KL11AB2432";
bool isPrevIsNum = false;
bool isPrevIsChar = false;
String result = "";
for (int i = 0; i < data.length; i ) {
bool isIntData = isInt(data[i]);
if (isIntData) {
isPrevIsChar = false;
if (isPrevIsNum) {
result = "$result${data[i]}";
} else {
result = "$result ${data[i]}";
isPrevIsNum = true;
}
} else {
isPrevIsNum = false;
if (isPrevIsChar) {
result = "$result${data[i]}";
} else {
result = "$result ${data[i]}";
}
isPrevIsChar = true;
}
}
print(result.trim()); // KL 11 AB 2432
}
我認為條件可以在上層合并,但為了清楚起見,我一直這樣。可能還有其他捷徑??。
uj5u.com熱心網友回復:
這是我測驗過的最小代碼效率O(n)解決方案:
expect(trimNumString("KL11AB2432"), "KL 11 AB 2432"); // true
這里是:
String trimNumString(String text, {String separator = " "}) {
String result = "";
List<String> textAsList = text.split("");
for (int index = 0; index < testAsList.length; index = 1) {
bool hasReachedTheEdOfList = (index 1) >= testAsList.length;
bool hasNotReachedTheEdOfList = !hasReachedTheEdOfList;
int? currentElement = int.tryParse(testAsList[index]);
int? nextElement;
if (hasNotReachedTheEdOfList) {
nextElement = int.tryParse(testAsList[index 1]);
} else {
separator = "";
}
if ((currentElement == null && nextElement is int) ||
(currentElement is int && nextElement == null)) {
result = testAsList[index] separator;
continue;
}
result = testAsList[index];
}
return result;
}
您可以像這樣從方法呼叫中更改所需的分隔符
enter code here
trimNumString("KL11AB2432", separator: " ");
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/516006.html
標籤:扑镖
