简体   繁体   中英

Format a string into a specific format

Currently i have a 9 String number

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM