[英]Format a string into a specific format
Currently i have a 9 String number 目前我有一个9字符串数字
String s = 123456789
how can i convert this string into this kind of format? 我如何将这个字符串转换成这种格式?
String newS = 12 - 34 - 5678 - 9
I hope this will help you. 我希望这能帮到您。
public static String formatString(String str) {
return str.substring(0, 1) + " - " + str.substring(2, 3) + " - " + str.substring(4, 7) + " - " + str.substring(8);
}
With Java8 streams you can get a cleaner version... 使用Java8流,您可以获得更干净的版本...
String s = "123456789";
AtomicInteger pos = new AtomicInteger();
String newS = IntStream.of(2, 2, 4, 1)
.mapToObj(n -> s.substring(pos.getAndAdd(n), pos.get()))
.collect(Collectors.joining(" - "));
You can use a regular expression: 您可以使用正则表达式:
String s = "123456789";
Pattern pattern = Pattern.compile("(\\d{2})(\\d{2})(\\d{4})(\\d)");
Matcher matcher = pattern.matcher(s);
String formatted = matcher.find() ?
matcher.group(1) + " - " + matcher.group(2) + " - " + matcher.group(3) + " - " + matcher.group(4) :
"";
System.out.println(formatted); // 12 - 34 - 5678 - 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.