Arifah Azhar
Arifah Azhar

Reputation: 227

Concatenate a string before the last occurrence of any character

I want to concatenate a string before the last occurrence of any character.

I want to do something like this:

addToString(lastIndexOf(separator), string);

where "ddToString" is a function that would add the "string" before the "lastIndexOf(separator)"

Any ideas?

One way I thought of is making string = string + separator. But, I can't figure out how to overload the concatenate function to concatenate after a particular index.

Upvotes: 4

Views: 5168

Answers (4)

lancegerday
lancegerday

Reputation: 762

You should look in Java's api at http://download.oracle.com/javase/7/docs/api/ and use the String Classes substring(int beginIndex)method after you find the index of your specified character so

public String addToString(String source, char separator, String toBeInserted) {
        int index = source.lastIndexOf(separator); 
        if(index >= 0&& index<source.length())
    return source.substring(0, index) + toBeInserted + source.substring(index);
        else{throw indexOutOfBoundsException;}
}

Upvotes: 3

jli
jli

Reputation: 6623

The simple way is:

String addToString(String str, int pos, String ins) {
    return str.substring(0, pos) + ins + str.substring(pos);
}

Upvotes: 1

moshbear
moshbear

Reputation: 3322

You need to use StringBuffer and method append(String). Java internally converts + between Strings into a temporary StringBuffer, calls append(String), then calls toString() and lets the GC free up allocated memory.

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234797

Try this:

static String addToString(String source, int where, String toInsert) {
    return source.substring(0, where) + toInsert + source.substring(where);
}

You'll probably want to add some parameter checking (in case character isn't found, for instance).

Upvotes: 2

Related Questions