Turtle
Turtle

Reputation: 1389

Disregarding first part of split string

If I have a string like : 1234_my_string.txt is there a better way than the one provided to lop off the 1234_ so the value of the string would be equal to my_string.txt?

To be clear, I want to discard everything up to and including the first '_' in the string. The string is not neccessarily equal to "1234_my_string.txt". The length of the characters before the first '_' is not known.

Pseudocode:

String str = "1234_my_string.txt";
do foo
str == my_string.txt

Here is a working example I currently have which checks the value of str then splits and rejoins the string to get the desired result. The size of characters I want to lop off is not known. I do not think this is very efficient:

        if(str != null && !str.equals("") )
        {
            String [] strParts = str.split("_");
            val = "";

            for (int i = 1; i < strParts.length; i++)
            {
                str += strParts[i];
                str += "_";
            }

            str = str.substring(0, str.length()-1);
        }

Upvotes: 0

Views: 61

Answers (2)

Pshemo
Pshemo

Reputation: 124265

Probably simplest solution would be

str = str.substring(str.indexOf('_') + 1);

If you are sure that your string will contain at least one _ you can also use something like:

str = str.split("_", 2)[1];
//        splits max into two parts
//        [1] get second part (the one after "_")

Upvotes: 7

azurefrog
azurefrog

Reputation: 10945

If you just want to get rid of everything up to and including the first _, one easy way would just be to use a regular expression and replace that section with "".

e.g.

String str = "1234_my_string.txt";
str = str.replaceFirst("[^_]*_", "");
System.out.println(str);  // my_string.txt

Upvotes: 4

Related Questions