2

I have a string like this.

PER*IP**TE**1234567890*EM*[email protected]

How can I parse the string into multiple lines like this in Java?

PER
IP
TE
//Empty String
EM
1234567890
[email protected]
2
  • 4
    Why is there an empty string after TE, but not after IP? Where has EM gone? Commented Feb 16, 2021 at 15:41
  • 1
    is it giving empty string before the numbers? Commented Feb 16, 2021 at 15:53

3 Answers 3

5

You could use a regex replacement:

String input = "PER*IP**TE*1234567890*EM*[email protected]";
String output = input.replaceAll("\\*", "\n");
System.out.println(output);

This prints:

PER
IP

TE
1234567890
EM
[email protected]
Sign up to request clarification or add additional context in comments.

Comments

4

You can use String#split. Since * is a regular expression metacharacter, you need to escape it with a backslash or use Pattern#quote.

Arrays.stream("PER*IP**TE**1234567890*EM*[email protected]".split(Pattern.quote("*")))
   .forEach(System.out::println);

Comments

4
String newstring = string.replace("*", "\n");
System.out.println(newstring);

now if you don't want that the empty line show up, use this:

String string = "PER*IP**TE**1234567890*EM*[email protected]"
String newstring = string.replaceAll("\\*+","*").replace("*", "\n");
System.out.println(newstring);

1 Comment

yes, sorry, misspell

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.