-3

I am getting an input string containing digits with comma (,) separated like these formats

1) X,X

2) X,XX

3) XX,X

My desired format is XX,XX.

I want if I get the input string like in above 1,2,3 formats it should be formatted as my desired format XX,XX.

For example,

1) If I get a string in this format 1,12. I want to put a zero before 1 like this 01,12.

2) If I get a string in this format 1,1. I want to put a zero before and ofter 1 like this 01,10.

3) If I get a string in this format 11,1. I want to put a zero after the last 1 like this 11,10.

Any help will be highly appreciated, thanks in advance.

Abid Khan
  • 2,451
  • 4
  • 22
  • 45

4 Answers4

0

You can use regex pattern to format in your specific pattern using Lookaround

(?=^\d,\d\d$)|(?<=^\d\d,\d$)|(?<=^\d,\d$)|(?=^\d,\d$)

Online demo

Here we are using three combination of data as given by you and empty space is replaced by zero.

Sample code:

String regexPattern="(?=^\\d,\\d\\d$)|(?<=^\\d\\d,\\d$)|(?<=^\\d,\\d$)|(?=^\\d,\\d$)";
System.out.println("1,12".replaceAll(regexPattern, "0"));
System.out.println("1,1".replaceAll(regexPattern, "0"));
System.out.println("11,1".replaceAll(regexPattern, "0"));

output:

01,12
01,10
11,10
Braj
  • 46,415
  • 5
  • 60
  • 76
0

Feed in your number to the function, and get the desired String result.

    public  static String convert(String s){
    String arr[] = s.split(",");

    if(arr[0].length()!=2){
        arr[0] = "0"+arr[0];
    }

    if(arr[1].length()!=2){
        arr[1] = arr[1]+"0";
    }

    return arr[0]+","+arr[1];

}

But it only works in the format described above.

rd22
  • 1,032
  • 1
  • 18
  • 34
0

If your goal is to print these strings, you could use the format method, and leading and trailing zeroes.

https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

JoshM33k
  • 11
  • 2
0
Object[] splitted = input.split(",");
System.out.println(String.format("%2s,%-2s", splitted).replace(' ','0'));