inserting a character in a string...

Go down

inserting a character in a string...

Post  sukesh on Tue Sep 11, 2007 12:19 am

Hi.
I have a problem. I want to insert a character at some specified position in a string in J2ME, which is already consisting an array of characters. I cant use StringBuffer due to some reasons.

How can I do that. There is no method available in the API.

sukesh

Posts : 8
Join date : 2007-09-10

View user profile

Back to top Go down

Re: inserting a character in a string...

Post  guantana on Tue Sep 11, 2007 1:52 am

Hi sukesh,

Since there is no method to insert a character into String, and u can't use Stringbuffer, I would suggest you to write your own method for inserting character into string. Here is the sample code:


private static String insert(String inputStr, char c, int pos)throws IllegalArgumentException{

if(pos < 0 || pos > inputStr.length()){
throw new IllegalArgumentException("Inappropriate pos");
}

char[] inputArray = inputStr.toCharArray();
char[] outputArray = new char[inputArray.length + 1];
System.arraycopy(inputArray, 0, outputArray, 0, pos);
outputArray[pos] = c;
System.arraycopy(inputArray, pos , outputArray, pos + 1, inputArray.length - pos);

return new String(outputArray);
}

Guantana.
avatar
guantana

Posts : 22
Join date : 2007-09-09
Location : New Delhi, India

View user profile http://guantana.blogspot.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum