Monday, December 19, 2011

Remove Character From String1 which are present in String2

You are given two strings, remove the characters from the first string which are present in the second string.

Algorithm: Let first input string be “test string” and the string which has characters to be removed from first string be “mask”
1: Initialize:
res_ind = 0 /* index to keep track of processing of each character in i/p string */
ip_ind = 0 /* index to keep track of processing of each character in the resultant string */

2: Construct count array from mask_str. Count array would be:
(We can use Boolean array here instead of int count array because we don’t need count, we need to know only if      character is present in mask string)
count['a'] = 1
count['k'] = 1
count['m'] = 1
count['s'] = 1

3: Process each character of the input string and if count of that character is 0 then only add the character to the resultant string.
str = “tet tringng” // ’s’ has been removed because ’s’ was present in mask_str but we we have got two extra characters “ng”
ip_ind = 11
res_ind = 9

4: Put a ‘′ at the end of the string if required.

Reference -

Java code sample is :

public class RemoveFirstFromSecond {
public static void main(String[] args) {
String first = "this is a test";
String second = "mask";
boolean bit[] = new boolean[256]; //boolean are defaulted to false
//Set the bits on bit[] for the mask string
for(int i=0;i<second.length();i++){
bit[second.charAt(i)] = true;
}
//This is not good, we can use StringBuffer
//char[] is just for the proof of concept
char[] result = new char[first.length()];
for(int i=0,j=0;i<first.length();i++){
if(bit[first.charAt(i)]==false){
result[j] = first.charAt(i);
j++;
}
}
String resultstr = new String(result);
System.out.println("Result - " + resultstr);
}
}//:~

0 comments:

Post a Comment