Parsing information out of the center of a String in Java
Let's say I have the following string of text:
"first:c开发者_如何学运维enter:last"
I want to extract only "center" from this string. However, I do not know what will be in the beginning, the end, or the center of the string. All I know is that colons will separate the three pieces of the string and the part I need from the string is the piece in-between the colons.
Using Java, what is the cleanest way that I could accomplish this task?
Thank you very much in advance for your time.
Since you only want the center you can perform a substring using the appropriate indices. This will be more efficient than the split() approach as you'll create fewer string and array instances.
public class Main {
public static void main(String[] args) {
String fullStr = "first:center:last";
int firstColonIndex = fullStr.indexOf(':');
int secondColonIndex = fullStr.indexOf(':', firstColonIndex + 1);
String centerStr = fullStr.substring(firstColonIndex + 1, secondColonIndex);
System.out.println("centerStr = " + centerStr);
}
}
A non-RegEx based solution which I believe is the fastest:
String string = "left:center:right";
String center = string.substring(string.indexOf(':') + 1, string.lastIndexOf(':'))
try{
String str="first:center:last";
String result = str.split(":")[1];
}catch(ArrayIndexOutOfBounds aex){
//handle this scenario in your way
}
Logically, I would have gone (of this effect):
String[] splits = string.split(":");
String centerStr = splits[1];
Use String.split()
and take the second item in the array.
http://www.rgagnon.com/javadetails/java-0438.html
精彩评论