Goofy
Goofy

Reputation: 6128

Get the data after colon and display in different lines

i have a String like this :

"I have 2 friends: (i) ABC (ii) XYZ"

Now how to display like this:

I have 2 friends:

(i) ABC
(ii) XYZ

I am displaying the data dynamically so i have to check if the string contains :(colon).

i tried getting like this string.contains(":") but i am not getting how to proceed further?

Upvotes: 1

Views: 1148

Answers (4)

Arsen Alexanyan
Arsen Alexanyan

Reputation: 3141

You can use indexOf and substring methods of the String class to gain this.

System.out.println(str.substring(0, str.indexOf('(', 0)));
System.out.println();
System.out.println(str.substring(str.indexOf('(', 0), str.indexOf('(', str.indexOf('(', 0) + 1)));
System.out.println(str.substring(str.indexOf('(', str.indexOf('(', 0) + 1)));

Upvotes: 2

Liam
Liam

Reputation: 1041

The following will solve your specific problem:

String str = "I have 2 friends: (i) ABC (ii) XYZ";

int indexOfColon = str.indexOf(":");
int lastIndexOfOpenParenthesis = str.lastIndexOf("(");

String upToColon = str.substring(0, indexOfColon);
String firstListItem = str.substring(indexOfColon + 1, lastIndexOfOpenParenthesis);
String secondListItem = str.substring(lastIndexOfOpenParenthesis);

String resultingStr = upToColon + "\n\n" + firstListItem + "\n" + secondListItem;

Check out the java.lang.String documentation for all your string manipulation needs! (within Java)

Upvotes: 0

Aquatoad
Aquatoad

Reputation: 788

String s = "I have 2 friends: (i) ABC (ii) XYZ";
s = s.replace(':',':\n');
s = s.replace('(','\n(');

(not a generalized solution, but assuming your "list of friends" formatting is constant and the colon indicates presence of the list... you can wrap in an if(s.contains(':')){ ... } block if needed)

Upvotes: 3

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

String s = "I have 2 friends: (i) ABC (ii) XYZ";
String [] parts = s.split (":");
System.out.println (parts [0]);
System.out.println ();
Matcher m = Pattern.compile ("\\([^)]+\\)[^(]*").matcher (parts [1]);
while (m.find ()) System.out.println (m.group ());

Output is:

I have 2 friends

(i) ABC 
(ii) XYZ

Upvotes: 2

Related Questions