Insert a String into a another String @ a specifi point
Hi,
I want to insert a String into another one at the exact point of the 3rd occurence of '>' in the String - is there a handy way to do this?
For example: String toInsert = "abc";
String original = "<hello><there><my><friend>";
and my combined String would look like:
"<hello><there><my>abc<friend>"
Thanks,
C
[413 byte] By [
adunkey10a] at [2007-11-27 2:44:44]

Hey friend,
Checkout the below example where we are making use of a util class "StringTokenizer" and separating set of strings and inserting the supposed value accordingly by assuming ">" as a delimter.
import java.util.StringTokenizer;
public class StringEditUtils{
public String make(String original,String toInsert,int pos){
int i = 0;
StringBuffer strbuf = new StringBuffer();
/*as per the condition separating string using a delimter ">" (closed angular brakets) */
String delim = ">";
StringTokenizer strToken = new StringTokenizer(original,delim);
while(strToken.hasMoreElements()){
strbuf.append(strToken.nextElement());
strbuf.append(delim);
i = i + 1;
// appends the string which is supposed to be inserted after specified position
if(i == pos)
strbuf.append(toInsert);
}
return strbuf.toString();
}
public static void main(String args[]){
StringEditUtils util = new StringEditUtils();
String toInsert = "abc";
String original = "<hello><there><my><friend>";
/*inserting "abc" at 3rd position */
System.out.println( util.make(original,toInsert,3) );
}
}
Hope this might help :)
REGARDS,
RaHuL
public static void main(String[] args) {
String original = "<hello><there><my><friend>";
char gt = '>';
String text = "abc";
int index = original.indexOf(gt, original.indexOf(gt, original.indexOf(gt)+1)+1)+1;
String newString = original.substring(0, index)+text+original.substring(index);
System.out.println(newString);
}
surround this code with a try catch block and handle appropriatelly the exceptions
Hope that helps