测试数据如
1a, 12a, 1ab, 12ab, 123a, 123abc
所以如果作为输入我们有:
String input = "1a";
输出将是
String number = "1";
String letter = "a";
就像您注意到的那样,在此字符串中有时有 1-3 个数字 (0-9),有时有 1-3 个字母 (A-Z)。
我的第一次尝试:
我尝试使用 .substring()
但它只有在例如总是有相同数量的数字或字母的情况下才会起作用
我的第二次尝试是:
.split(" ");
但只有在中间有空格或任何其他符号时它才会起作用。
附言。 感谢您在答案中的回应。我检查了你的大部分答案,它们都有效。 现在的问题是哪个最好?
最佳答案
没有正则表达式的简单解决方案: 找到第一个字母的索引并在此位置拆分字符串。
private String[] splitString(String s) {
// returns an OptionalInt with the value of the index of the first Letter
OptionalInt firstLetterIndex = IntStream.range(0, s.length())
.filter(i -> Character.isLetter(s.charAt(i)))
.findFirst();
// Default if there is no letter, only numbers
String numbers = s;
String letters = "";
// if there are letters, split the string at the first letter
if(firstLetterIndex.isPresent()) {
numbers = s.substring(0, firstLetterIndex.getAsInt());
letters = s.substring(firstLetterIndex.getAsInt());
}
return new String[] {numbers, letters};
}
给你:
splitString("123abc")
returns ["123", "abc"]
splitString("123")
returns ["123", ""]
splitString("abc")
returns ["", "abc"]
关于java - 如何在java中将字符串拆分为数字和字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49107010/