Wednesday, 19 August 2015

Program to replace character from the String using user defined method.

package com.JavaInterview.Programs;
/*How to replace characters from a string using user defined method .Here we have use  StringBuffer * ,you can also use StringBuilder.
*
* @author:http://javainterviewprograms.blogspot.in/

*/

public class CharacterReplace2 {

 //User method to replace characters from a string

 public static String replace(String s,char from,char to)
 {
  StringBuffer str=new StringBuffer(s.length());
 
  for(int i=0;i<s.length();i++)
  {
   if(s.charAt(i)==from)
   {
    str.append(to);
   }
   else
   {
    str.append(s.charAt(i));
   }
  }
  return str.toString();
 }

 public static void main(String args[])
 {
  String original="This is a JIP Example String";
 
  System.out.println("Original String : "+original);
 
  
  String changed=replace(original, 'i','*');
 
  System.out.println("Changed String :" + changed);
 }
}

Output:

Original String : This is a JIP Example String
Changed String :Th*s *s a JIP Example Str*ng


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...