Wednesday, August 13, 2008

JAVA: Method That Removes Specified Characters From String

I needed a method that can remove specified set of characters from a given string. I came up with this solution. This method takes two parameters.

1. First parameter is original String from which you want to remove the characters.
2. Second parameter is a string containing the characters that we want to remove from the original string.

EXAMPLE:

If we provide the following input:

removeFromString("MYRSH Blogs by Sabah u Din Irfan","asi");

The method will return the followin output:

MYRSH Blog by Sbh u Dn Irfn
///////////////////////////////////////////


public static String removeFromString(String str,String rem)
{
StringBuffer result=new StringBuffer();

char[] s = str.toCharArray();
char [] r = rem.toCharArray();

boolean [] flags =new boolean[128];

int len=str.length();
int src, dest;

for(src = 0 ; src < r.length; ++src )
{
//System.out.println("src="+src);
flags[r[src]]=true;
}

src = 0 ; dest = 0 ;
while(src < len)
{
if( !flags[(int)s[src]] )
{
result.append(s[src]);
}
++src;
}
return result.toString();
}

No comments: