Salesforce.com

  www.salesforce.com
  www.salesforce.com

Interview Question

Quality Engineer Interview Seattle, WA

Write a Java function that counts the number of "words" in

  where words are *only* delimited by space characters (no punctuation, very basic). Write unit tests for this function.
Answer

Interview Answer

1 Answer

0

static int CountNumberOfWords(char[] arr)
        {
            if (arr.Length < 0)
            {
                return -1;
            }

            int numOfWords = 0;
            bool atWord = false;

            for (int i = 0; i < arr.Length; ++i)
            {
                if (!atWord && arr[i] != ' ') // encounter character
                {
                    atWord = true;
                    numOfWords++;
                }
                else if (atWord && arr[i] == ' ')
                {
                    atWord = false;
                }
            }
            return numOfWords;
        }

Jigargosha on Jul 10, 2012

Add Answers or Comments

To comment on this Question, Sign In with Facebook or Sign Up