Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

2. You are to write a subroutine/function which will expect a string as inputThe

ID: 3587921 • Letter: 2

Question

2. You are to write a subroutine/function which will expect a string as inputThe function should count the total number of words in the string calculated as the number of blocks of space characters plus one. The subroutine should then return this quantity as an integer. Two or more consecutive space characters should only count as one block. Example: The string "Bob has twelve apples." should report 4 words because it contains three space characters. Note that the ASCII code for space is Ox20. Example: The string "Bob has twelve apples ." should also report 4 words because it contains three blocks of space characters.

Explanation / Answer

Hi,

You have not specified the programming language to code this problem. I am solving it in both Java and C++. Please use the code whichever needed.

Java Code-

public class HelloWorld{

static int wordcount(String string)  
{  
int count=0;  
  
char ch[]= new char[string.length()];
for(int i=0;i<string.length();i++)  
{  
ch[i]= string.charAt(i);  
if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )  
count++;  
}  
return count;  
}  
public static void main(String[] args) {  
String string =" India Is My Country bbb";  
System.out.println(wordcount(string) + " words.");
}  
}

C++ Code-

#include <iostream>

using namespace std;

int main( )
{
char str[80];
int flag=0;
cout << "Enter a string: ";
cin.getline(str,80);

int words = 0;

for(int i = 0; str[i] != ''; i++)
{
if ((str[i] == ' '||str[i]==',')&&flag==0)
{
flag=1;
words++;
}
else if(str[i]!=' '&&str[i]!=',')
flag=0 ;
}

cout << "The number of words = " << words+1 << endl;

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote