gursahib.singh.sahni
gursahib.singh.sahni

Reputation: 1597

Efficient way to perform various String operations

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

Answers (3)

rogue-one
rogue-one

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

Ron
Ron

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

String.substring()

get the last index

String.length() -1

the last character

s.charAt(s.length()-1);

get nth character in a string

String.charAt()

comparisons

String.compareTo()

string contains a string or not

String.contains()
You can also use String.toLowerCase() on both if necessary

Upvotes: 0

Abdul Salam
Abdul Salam

Reputation: 238

Since you are not manipulating the strings, you can use String or StringUtils instead of StringBuilder

Upvotes: 0

Related Questions