Replace space in string by $#$ in java


In this core java programming tutorial we will write a program to Replace all $#$ in string by space in java.



Write a program to Replace space in string by $#$ in java.

entered string = java made so easy
output string  = java$#$made$#$so$#$easy

Must read: Matrix related programs in java.
                       Pattern/Pyramid generating programs in java.


Example/ Full Program/SourceCode to Replace all $#$ in string by space in java>
/** Copyright (c), AnkitMittal  JavaMadeSoEasy.com */
public class ReplaceSpecialCharExample {
   public static void main(String[] args) {
         
          String input="java$#$made$#$so$#$easy";
          //input="java$#$made$#$so$#$easy$";      //for testing
          //input="$java$#$made$#$so$#$easy$#";   //for testing
          //input="$#java$#$made$#$so$#$easy$#";  //for testing
         
          System.out.println("entered string = "+input);
          System.out.println("output string  = "+replaceSpecialChar(input));
         
   }
   /*
   * Method replaces '$#$' with space.
   */
   public static String replaceSpecialChar(String input) {
          char ch[]=input.toCharArray();
          int length=ch.length;
         
          for (int i = 0; i < length-2; i++) {
                 if ( i+2<length && ch[i] == '$' && ch[i+1] =='#' && ch[i+2] == '$' ) {
                       ch[i]=' ';
                       int iRef=i+1;
                       while(iRef<length-2){
                              ch[iRef]=ch[iRef+2];
                              iRef++;
                       }
                       length-=2;
                 }
          }
         
          char chNew[]=new char[length] ;
          for (int i = length - 1; i >= 0; i--) {
                 chNew[i]=ch[i];
          }
          return(new String(chNew));
   }
}
/*OUTPUT
entered string = java$#$made$#$so$#$easy
output string  = java made so easy
*/


So in this core java programming tutorial we wrote a program how to Replace all $#$ in string by space in java.

Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.




RELATED LINKS>










No comments:

Post a Comment