Pergunta de entrevista da empresa Salesforce

Write a Java function that counts the number of "words" in a string, where words are *only* delimited by space characters (no punctuation, very basic). Write unit tests for this function.

Resposta da entrevista

Sigiloso

10 de jul. de 2012

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; }