-2

String

string1 = 3N10:35, 4510:36, 3N10:35, 4510:36, 3N10:35, 4510:36, 3N10:35

after splitting it should be as below

"3N10:35, 4510:36, 3N10:35, 4510:36" -- length 34 chars

"3N10:35, 4510:36, 3N10:35-----------" -- length 34 char (appending with space at the end)


String

string2=3N10:35, 4511:36, 3N12:35, 4516:36, 3N19:35, 4521:36, 3N19:35, 3N19:18, 4522:31, 3N22:12

after splitting it should be as below

"3N10:35, 4511:36, 3N12:35, 4516:36" - length 34 chars

"3N19:35, 4521:36, 3N19:35, 3N19:18" - length 34 chars

"4522:31, 3N22:12------------------" - length 34 char (appending with space at the end)

how to achieve in Java

MT0
  • 143,790
  • 11
  • 59
  • 117
Deep
  • 3
  • 2
  • can you please give me an example on how to split on every 4th comma – Deep Jun 07 '20 at 16:40
  • 1
    Welcome to StackOverflow. Please follow the posting guidelines in the help documentation, as suggested when you created this account. [on topic](https://stackoverflow.com/help/on-topic), [How to Ask](https://stackoverflow.com/questions/how-to-ask), and ... [the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) apply here. StackOverflow is not a design, coding, research, or tutorial resource. However, if you follow whatever resources you find online, make an honest solution attempt, and run into a problem, you'd have a good example to post. – Harshal Parekh Jun 07 '20 at 16:58

1 Answers1

0

The following solution works fine:

String[] arr = s.split("(?<=\\G(.{7}\\,\\s?){4}+)"); // split by each 4-th comma optionally followed by a space

Arrays.stream(arr)
      .map(st -> String.format("[%-34.34s]", st)) // set required width, removing redundant ", " at the end, using [] to display appended whitespaces
      .forEach(System.out::println);

Output for the input strings:

[3N10:35, 4510:36, 3N10:35, 4510:36]
[3N10:35, 4510:36, 3N10:35         ]

[3N10:35, 4511:36, 3N12:35, 4516:36]
[3N19:35, 4521:36, 3N19:35, 3N19:18]
[4522:31, 3N22:12                  ]
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42