# Word Count Coderbyte Solution

0

Have the function WordCount(str) take the str string parameter being passed and return the number of words the string contains (ie. "Never eat shredded wheat" would return 4). Words will be separated by single spaces. Solution in Java

import java.util.Scanner;

public class WordCount {
int WordCount(String str) {
return str.split("\\s").length;
}

public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
WordCount c = new WordCount();
System.out.print(c.WordCount(s.nextLine()));
}
}

Solution in JavaScript

I am going to convert str to an Array breaking each word into an Array entry when there is a space. Then return the length of the Array which is the number of words in the string. Using the JavaScript language, have the function WordCount(str) take the str string parameter being passed and return the number of words the string contains (ie. "Never eat shredded wheat" would return 4). Words will be separated by single spaces.

Steps for solution

1) Convert string to an array breaking on space.

2) Return array length since this is the number of words

function WordCount(str) {

return str.split(" ").length;
}

Solution in Python

Using the Python language, have the function WordCount(str) take the str string parameter being passed and return the number of words the string contains (ie. "Never eat shredded wheat" would return 4). Words will be separated by single spaces.

def WordCount(str):
return len(str.split())