在字符串飞镖中的数字和字母之间加空格



我希望字符串中的数字和字母之间有空格。示例:字符串=";KL11AB2432";;到字符串=";KL 11 AB 2432";;

你们都太努力了。获取正则表达式!

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(" ");
}
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

我正在使用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
}

我认为条件可以在上层合并,但为了明确起见,我一直保持这样。可能还有其他捷径😅.

这是我测试的最低代码效率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: " ");

最新更新