将字符串格式化为特定格式

时间:2018-11-13 07:13:42

标签: java string

当前我有一个9字符串数字

String s = 123456789

如何将字符串转换为这种格式?

String newS = 12 - 34 - 5678 - 9

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

试试这个:

String

答案 2 :(得分:0)

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

答案 3 :(得分:0)

您可以使用正则表达式:

    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