Reputation: 1597
I have a Script in which i have to extract string from strings, get the last index, get nth character in a string, comparisons, string contains a string or not etc etc. I would like to know the best method/ practice to do such operations on strings in java. Should i use StringBuilder
all the time to perform the above operations. In few cases i have used regular expressions
to find strings.
So what should i use?
Scenario is : loads of comparisons and indexes have to found. Thanks.!
example :
String name = "application/octet-stream; name=\"2012-04-20.tar.gz\""; // get 2012-04-20.tar.gz
Pattern pattern = Pattern.compile("\"(.*?)\"");
Matcher matcher = pattern.matcher(name);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
String date = " Number 4, December 2013";
String year = date.substring(date.lastIndexOf(" ")+1);
String month = date.substring(date.indexOf(',')+2,date.indexOf(" ",date.indexOf(',')+2 ));
date = year+getMonth(month)+"01";
System.out.println(date);
Like above, many other extraction of string within string.
Upvotes: 1
Views: 164
Reputation: 11577
When you deal with large amount of String object use String intern
function wisely to conserve heap space and eliminate object creation overhead. refer here for more information
Upvotes: 1
Reputation: 1508
All of these operations can be done with the String class, see below for the methods you should use.
extract string from strings
get the last index
the last character
s.charAt(s.length()-1);
get nth character in a string
comparisons
string contains a string or not
String.contains()
You can also use String.toLowerCase() on both if necessary
Upvotes: 0
Reputation: 238
Since you are not manipulating the strings, you can use String or StringUtils instead of StringBuilder
Upvotes: 0