How to add spaces to a variable

Hi folks,
I am using the following substring code to add spaces to a variable. Just wondering if there is cleaner way to do this?

def NUM = "716423947";
def NumPart1 = NUM.substring(0, 3)
def NumPart2 = NUM.substring(3, 6)
def NumPart3 = NUM.substring(3, 6)
def NumResult = NumPart1 + " " + NumPart2 + " " + NumPart3
println("NumResult: " + NumResult)

My output is what I expect it to be β€œ716 423 947”

Found this solution using regex on StackOverflow:

1 Like
int n = "716423947".toInteger()
String s = String.format("{%,d}", n).replace(",", " ");

println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> " + s)

But I’m not a fan of that kind of jiggerypokery :upside_down_face:

1 Like

Thanks @Brandon_Hein & @Russ_Thomas.
I really appreciate your feed-back.

Both solutions work much better than mine…

I will use this one; it works really well :wink:

String str = "123456789";
String val = "3";   //use 3 to insert a space after every 3 characters
String result = str.replaceAll("(.{" + val + "})", "\$1 ").trim();
System.out.println(result);
1 Like