Reputation: 49
Please help me to split string like this "mumbai (or) pune" using java.
I want the string after ")", I tried using string.split()
but not working on above String format.
my expected output is "pune".
input:
String abc="mumbai (or) pune"
output:
String result="pune".
Upvotes: 0
Views: 94
Reputation: 4907
You can split it into parts:
String abc="mumbai (or) pune"
String result = "pune";
String[] parts = abc.split(" ");
String partOne = parts[0];
String partTwo = parts[2];
if (partOne == result){
System.out.println(partOne);
}
else{
System.out.println(partTwo);
}
Upvotes: 1
Reputation: 3017
There are many ways to do the simple thing which you are looking for. Best approach: Read of String Operations in Java
Following are just some ways to achieve what you need:
public static void main(String[] args)
{
String output1 = "mumbai (or) pune";
String output2 = output1.split("or\\) ")[1];
String output3 = output1.substring(output1.indexOf(")")+2);;
System.out.println(output1);
System.out.println(output2);
System.out.println(output3);
}
Upvotes: 0
Reputation: 14471
It doesn't work because )
is special in regex. Escape the regex with \\
.
Use string.split("\\)")[1].trim();
instead.
Upvotes: 1
Reputation: 1680
If your input string is always similar to the one you showed:
yourString.split("\\)")[1].trim();
Upvotes: 1
Reputation: 36304
A replace would be actually more efficient here.
Use :
String abc="mumbai (or) pune";
abc = abc.replaceAll(".*\\s+(\\w+)","$1");
// abc will be "pune" here
Upvotes: 0
Reputation: 172378
Try this:
String s = "mumbai (or) pune";
String result = s.substring(s.lastIndexOf(')') + 1).trim();
Upvotes: 0