I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

Thursday Code Puzzler: Some String Manipulation

05.09.2012
| 4567 views |
  • submit to reddit

Another Thursday, another puzzle. The idea is simple: solve the coding problem as efficiently as you can, in any language or framework that you think is suitable. This week's one is a bit more practical than previous puzzles.

Note: Even though there really is nothing stopping you from finding a solution to this on the internet, try to keep honest, and come up with your own answer.  It's all about the participation!

Remove Characters From A String

Write a method that takes two String parameters string1 and string2. The method must remove all the characters from string2 that appeared in string1. Here's an example to make the problem clearer: 

string1: code

string2: puzzle

result: puzzl

If you wish, you can express the efficiency of the algorithm you come up with using Big O notation.

 

 

Comments

Sathish Kumar replied on Thu, 2012/05/10 - 4:18am

public void  compareStrings(String string1, String string2) { int[] arrChar = new int[26]; char[] string1Char = new char[string1.length()]; char[] string2Char = new char[string2.length()];
string1Char = string1.toCharArray(); string2Char = string2.toCharArray(); for (int i=0;i<string1Char.length;i++ ) { int asciicode = (int)string1Char[i]; arrChar[asciicode-97] += 1; } for (int j=0;j<string2Char.length;j++ ) { int asciicode = (int)string2Char[j]; if ( arrChar[asciicode - 97] == 0 ) { System.out.print(string2Char[j]); } } }

Philipp Neumann replied on Thu, 2012/05/10 - 4:59am

strg2.replaceAll('['+strg1+']', "")

James Sugrue replied on Thu, 2012/05/10 - 5:28am in response to: Philipp Neumann

I see where you're going with that one :) But it's more fun to do the lower level algorithm instead of using the utility functions available 

James 

Motaz Mohamed replied on Thu, 2012/05/10 - 6:09am

public String getmatch(String str1, String str2) { StringBuilder strbBuilder = new StringBuilder(str2); for (char c : str1.toCharArray()) { //str2=strbBuilder.toString(); int index = str2.indexOf(c); if (index != -1) { while (index >= 0) { System.out.println(index); strbBuilder.deleteCharAt(index); str2=strbBuilder.toString(); index = str2.indexOf(c); } } } if (strbBuilder != null && strbBuilder.length() > 0) { return strbBuilder.toString(); } else { return ""; } }

Reinhard Nägele replied on Thu, 2012/05/10 - 6:42am

import com.google.common.primitives.Chars;

public static String removeCharsFromString(final String s, final String charsToRemove) {
    char[] chars = s.toCharArray();

    CharBuffer buf = CharBuffer.allocate(charsToRemove.length());
    for (char c : charsToRemove.toCharArray()) {
        if (Chars.indexOf(chars, c) == -1) {
            buf.append(c);
        }
    }

    return buf.flip().toString();
}

Chirag Visavadia replied on Thu, 2012/05/10 - 6:54am

private static String getUniqueString(String str1, String str2) {

		/**
		 * Approach : Check all the char of str2 for existence in str1 and if
		 * NOT exists then print.
		 */
		long startTime = Calendar.getInstance().getTimeInMillis();

		HashSet<Character> alreadyProcessed = new HashSet<Character>();

		for (int i = 0; i < str2.length(); i++) {

			/**
			 * Removing extra cycle for repetitive Char
			 */
			if (alreadyProcessed.contains(str2.charAt(i)))
				break;

			boolean charExists = false;
			for (int j = 0; j < str1.length(); j++) {
				if (str2.charAt(i) == str1.charAt(j)) {
					charExists = true;

					/**
					 * Require to reduce extra cycle for repetitive Char.
					 */
					alreadyProcessed.add(str2.charAt(i));

					/**
					 * We are using break hear because it will reduce
					 * unnecessary time for repetitive char.
					 */
					break;
				}
			}

			if (!charExists)
				System.out.print(str2.charAt(i));
		}
		long endTime = Calendar.getInstance().getTimeInMillis();
		System.out.println("\nStart Time: " + startTime + " - End Time: " + endTime);
		System.out.println("Approach Total Time(mills) : " + (endTime - startTime));

		/**
		 * Approach Ends
		 */

		return null;
	}

Bowen Ma replied on Thu, 2012/05/10 - 10:32am

ruby: "puzzle".delete('code') = "puzzl" which means the function is : def unique_string string1, string2 string2.delete(string1) end

Bit Twiddler replied on Thu, 2012/05/10 - 5:00pm

    // Well, it's a solution!! :)

    String removeChars(final String input, final String removed) {
        byte[] charTable = new byte[8192];
        for(int i = 0 ; i < removed.length() ; i++) {
            char ch = removed.charAt(i);
            charTable[ch / 8] |= (1 << (ch & 7));
        }
        StringBuilder sb = new StringBuilder(input.length());
        for(int i = 0 ; i < input.length() ; i++ ) {
            char ch = input.charAt(i);
            if((charTable[ch / 8] & (1 << (ch & 7))) == 0) {
                sb.append(ch);
            }
        }
        return sb.toString();
    }

Jason Holbrook replied on Thu, 2012/05/10 - 5:04pm

public static String removeCharacters(String str, String removeChars) {
   StringBuilder sb = new StringBuilder();
   StringTokenizer st = new StringTokenizer(str, removeChars);
   while(st.hasMoreTokens()) {
      sb.append(st.nextToken());
   }
   return sb.toString();
}

Justin Julicher replied on Thu, 2012/05/10 - 9:41pm

 public static String removeChars(String string, String removeString) {
        char[] removeChars = removeString.toCharArray();
        Arrays.sort(removeChars);
        char[] array = string.toCharArray();
        CharBuffer buffer = CharBuffer.allocate(array.length);
        for (char c : array) {
            if (Arrays.binarySearch(removeChars, c) < 0) {
                buffer.append(c);
            }
        }
        return buffer.flip().toString();
    }

Ian Mcintosh replied on Fri, 2012/05/11 - 10:03am

def solver(s1: String, s2: String) = s2.filterNot(s1.contains(_))

Jason Holbrook replied on Fri, 2012/05/11 - 12:49pm in response to: Jason Holbrook

Testing the StringTokenizer solution against many of the other solutions is interesting. It is slower when the return string is different than the input string, but when the return string is the same as the input string it can test up to twice as fast as the the other solutions. So as always it depends on your environment for what is the better tradeoff. 

ebenezer raj replied on Fri, 2012/05/11 - 1:48pm

using q b except "code" inter b:"puzzle"

Luci Vuc replied on Tue, 2013/11/19 - 1:49am

import java.util.Scanner;

public class CharsRemover {
	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		String word1 = "", word2 = "";
		while(true){
			System.out.print("Enter String 1: ");
			word1 = scn.next();
			System.out.print("Enter String 2: ");
			word2 = scn.next();
			
			System.out.printf("\n- String 1: '%s', \n- String 2: '%s', \n- Result:   '%s'\n\n", 
					word1, word2, removeChars(word1, word2));
			
			System.out.print("Play again? y/n: ");
			if(!scn.next().equals("y")){
				break;
			}
		}
		scn.close();
		System.out.println("OK. Bye.");

	}

	public static String removeChars(String s1, String s2){
		StringBuilder sb = new StringBuilder(s2.subSequence(0, s2.length()));
		for(int y = 0; y < sb.length(); y++){
			for(int x = 0; x < s1.length(); x++){
				if(sb.charAt(y) == s1.charAt(x))
					sb.deleteCharAt(y);						
			}
		}
		return sb.toString();
	}
}

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.