In: Computer Science
using java language only write a code
Have the function StringChallenge(str) take the str string parameter being passed and return the number of words the string contains (e.g. "Never eat shredded wheat or cake" would return 6). Words will be separated by single spaces.
Examples
Input: "Hello World"
Output: 2
Input: "one 22 three"
Output: 3
------- you have the following code edit it to get the result
mport java.util.*;
import java.io.*;
class Main {
public static String StringChallenge(String str) {
// code goes here
return str;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(StringChallenge(s.nextLine()));
}
}
Find the code for the above question below, read the
comments provided in the code for better understanding. If found
helpful please do upvote this.
Please refer to the screenshot of the code to understand the
indentation of the code.
Copyable Code
import java.util.*; //to get unput form user
import java.io.*;
class Main {
// this method returns the number of words in the str
public static String StringChallenge(String str) {
// first separate the string as per space
String words[] = str.split(" ");
// now store the strign size in str
str = "" + words.length;
return str;
}
//main driver code of the program
public static void main(String[] args) {
//Scanner class to get user input
Scanner s = new Scanner(System.in);
System.out.print(StringChallenge(s.nextLine()));
}
}
Screenshot of code
Output