Join a line 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 adds the line " before " lastIndexOf (delimiter) "

Any ideas?

One of the ways I was thinking about is string = string + separator . But I can't figure out how to overload the concatenate function to concatenate after a specific index.

+4
source share
4 answers

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

 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;} } 
+3
source

Try the following:

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

You will probably want to add some parameter checking (in case the character is not found, for example).

+2
source

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

+1
source

A simple way is:

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

Source: https://habr.com/ru/post/1380446/


All Articles