Expedia

  www.expedia.com
  www.expedia.com

Interview Question

Software Development Engineer In Test (SDET) II Interview Bellevue, WA

Reverse each word of the string without reversing the order

  of the words this is a test BECOMES siht si a tset
Tags:
technical, algorithm
Answer

Interview Answer

2 Answers

0

public class ReverseWordsInString {

    public static void main(String[] args) {
        System.out.println("<<"+reverseWords(" hi There, how are a you ")+">>");

    }

    private static String reverseWords(String original) {
        if (original == null || original.isEmpty()) {
            throw new IllegalArgumentException("IP cannot be null or empty");
        }
        final Pattern p = Pattern.compile("[a-zA-Z]");
        final StringBuilder returnString = new StringBuilder();

        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < original.length(); i++) {
            if (p.matcher(String.valueOf(original.charAt(i))).matches()) {
                temp.append(original.charAt(i));
            } else {
                if (temp.length() > 0) {
                    returnString.append(reverse(temp.toString()));
                    temp = new StringBuilder();
                }
                returnString.append(original.charAt(i));
            }
        }

        if (temp.length() > 0) {
            returnString.append(reverse(temp.toString()));
        }
        return returnString.toString();
    }

    private static String reverse(String data) {
        StringBuilder ret = new StringBuilder();
        for (int i = data.length() - 1; i >= 0; i--) {
            ret.append(data.charAt(i));
        }
        return ret.toString();
    }

Anonymous on Oct 19, 2012
0

/// <summary>
    /// Recieve a string of words and returns the words reversed without changing the order.
    /// </summary>
Here's my C# method:

public static string ReverseWordsInSentence(string sentence)
    {

        char[] whiteSpace = " \t\n".ToCharArray();
        string[] words = sentence.Split(whiteSpace);

        int count = 0;
        foreach (string individualWord in words)
        {
            words[count] = new string(individualWord.ToCharArray().Reverse().ToArray());
            count++;
        }
        return string.Join(" ", words);
    }

Andrew on Nov 10, 2013

Add Answers or Comments

To comment on this, Sign In or Sign Up.