Blanca Hdez
Blanca Hdez

Reputation: 3563

Char and String manipulation in Java

A simple question that I don't know if Java has also a simple solution.

I have a string like: name.ext.ext.out.end

I need to get rid of .out, always the penultimate extension. Is there a kind of indexof(), but beginning from the end? I know how to do this in a rudimentary way, but maybe there are much better ones.

Upvotes: 0

Views: 1470

Answers (4)

William R
William R

Reputation: 185

You question is pretty simple: how to remove the penultimate. This is pretty simple but you have to do it in two passes... Here it is:

    /**
     * Returns the penultimate of a string.
     */
public static String getPenultimate( String str, char separator ){
    int pos1 = str.lastIndexOf(separator);
    if( pos1 > 0 ){
        String substr = str.substring(0, pos1 );
        int pos2 = substr.lastIndexOf(separator);
        if( pos2 > 0 ){
            return substr.substring(0, pos2) + str.substring(pos1);
        }
        return str.substring(pos1+1);
    }
    return null;
}

public static void main( String[] args){
    System.out.println( getPenultimate( "name.ext.v2.out.end", '.' ) );
    System.out.println( getPenultimate( "out.end", '.' ) );
    System.out.println( getPenultimate( "end", '.' ) );
}

The main() gives the following results:

    name.ext.v2.end
    end
    null 

null is returned when data is insufficient. separator is the dot to pass as parameter (the method is generic).

Upvotes: 0

Hunter McMillen
Hunter McMillen

Reputation: 61512

If you know that is will always be ".out" why not use the replace() method in the String class API.

String extension = ".out";
String name = "name.ext.ext.out.end";
String newName = name.replace(extension, "");

EDIT: Different Solution

String extension = ".out";
String name = "name.ext.ext.out.end";

//searches backward from the end of the string
name.lastIndexOf(extension, name.length());

Upvotes: 3

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46395

Get the index using lastIndexOf()

You could do replace() with specified string to be replaced by ""

Upvotes: 2

Bozho
Bozho

Reputation: 597076

There is lastIndexOf(..) which should do.

Upvotes: 3

Related Questions