Saturday, May 22, 2010

How to delete a single character from a string in java or c++ at anyposition?

Java solution:


presuming your original String is s1 and index is the character position, we will create a string s2 containig the required content.


OK:


String s2=new String( s1.subSequence( 0,index - 1 ) ) ; //create a string containig the first part (from start to the character)


s2.concat( s1.subSequence( index+1,s1.length( ) ) ) ; //add the characters remainig from the character after index to the end of the first string.





Now s2 contains the required characters.


There a several ways of doing this..this is the one that popped in my mind right now :).


Have fun


P.S.: pay no attention to the spaces I left. Theyu are there because, without the the line doesn't display right (I think yahoo makes some subtitutions or something), so just delete the funny spaces :D

How to delete a single character from a string in java or c++ at anyposition?
First you hae to have clear concept on how string works in C++ and Java.


In C++, String is an array of charectar. So deleting is like deleting an entry from array, delete move all values after the value to be deleted one space ahead.





In Java, String is immutable, that means you can not change string. Ofcourse you can create new one whenever you need.for Java use substring method of String class to get a substring containing all previous value and another one containing all value after the charectar. Then concate those two string.


No comments:

Post a Comment