开发者

Char and String manipulation in Java

开发者 https://www.devze.com 2023-03-22 10:51 出处:网络
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

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.


There is lastIndexOf(..) which should do.


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());


Get the index using lastIndexOf()

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


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号