Question

In: Computer Science

Complete the function, MycountWords in C++, which will count the number of words in a string....

Complete the function, MycountWords in C++, which will count the number of words in a string. We will have different word separators(such as newline(\n), spaces, special symbols(? | \ , . : ;) ) That will separate the words in the giving istringstream. Remember if a words is separated by a hyphen and followed by a new line, they're still one word. The function has an option to be sensitive to case and also avoid duplicates. for duplicates, this is a boolean value that checks whether a word is repeated or not if its set to true and sensitive case is if the word count is sensitive to case and differentiates two words based on their case. even though they have different cases, they are the same word hence duplicates.

complete this function based on the description above.

unsigned int MycountWords(istringstream & iss, bool Duplicate=false, bool SenstiveCase =false) {

}

Solutions

Expert Solution

DESCRIPTION :

The program takes a string and counts the number of words in it.

SOLUTION:

1. The program takes a string.

2. Using a for loop, the number of spaces in the string are counted.

3. The total number of words will be number of spaces plus 1.

4. The result is printed.

5. Exit.

C++ CODE

Here is the source code of C++ Program to Find the Number of Words in a Given Sentence. The program output is shown below.

#include<iostream>
#include<string.h>
using namespace std;
int main ()
{
    char str[50];
    int count = 0, i; 
    cout << "Enter a string : ";
    gets(str);
    for (i = 0; str[i] != '\0';i++)
    {
        if (str[i] == ' ')
            count++;    
    }
    cout << "Number of words in the string are: " << count + 1;
    return 0;
}

OUTPUT:

Case 1 :

Enter a string : Mosaic

Number of words in the string are : 1

Case 2 :

Enter a string : 1 2 3 4 5

Number of words in the string are : 5

Case 3 :

Enter string : The sun shines brightly.

Number of words in the string are: 4

Case 4 :

Enter string : One two     three\n four\tfive

Number of words in the string are: 5

EXTRA CODE :

There can be many solutions to this problem. Following is a simple and interesting solution.

The idea is to maintain two states: IN and OUT. The state OUT indicates that a separator is seen. State IN indicates that a word character is seen. We increment word count when previous state is OUT and next character is a word character.

Given a string, count number of words in it. The words are separated by following characters: space (‘ ‘) or new line (‘\n’) or tab (‘\t’) or a combination of these.

/* C++ program to count no of words 
from given input string. */
#include <bits/stdc++.h>
using namespace std; 
 
#define OUT 0 
#define IN 1 
 
// returns number of words in str 
unsigned countWords(char *str) 
{ 
    int state = OUT; 
    unsigned wc = 0; // word count 
 
    // Scan all characters one by one 
    while (*str) 
    { 
        // If next character is a separator, set the 
        // state as OUT 
        if (*str == ' ' || *str == '\n' || *str == '\t') 
            state = OUT; 
 
        // If next character is not a word separator and 
        // state is OUT, then set the state as IN and 
        // increment word count 
        else if (state == OUT) 
        { 
            state = IN; 
            ++wc; 
        } 
 
        // Move to next character 
        ++str; 
    } 
 
    return wc; 
} 
 
// Driver code
int main(void) 
{ 
    char str[] = "One two     three\n four\tfive "; 
    cout<<"No of words : "<<countWords(str); 
    return 0; 
} 

OUTPUT :

Number of words : 5

TIME COMPLEXITY :

O(n)


Related Solutions

Main Objective: Create a function collect_statistics to count the number of words and mean length of...
Main Objective: Create a function collect_statistics to count the number of words and mean length of words in each sentence This is my code so far but I am struggling to join the two functions together. I would appreciate the help! The sentence given as an example is : "Haven't you eaten 8 oranges today?" the mean length of this sentence is 4.5 for reference. Each sentence needs to be split up if given multiple sentences, assuming each sentence ends...
In this program: ================================================================== /* Program to count number of occurrences of a given string in...
In this program: ================================================================== /* Program to count number of occurrences of a given string in original string*/ #include <iostream> #include <cstring> #include <stdio.h> #include <iostream> using namespace std; int main() { const int SIZE = 40; char str[SIZE]; char str1[SIZE]; char searchString[SIZE]; int n; int l1, l2; int count = 0; printf("Enter a sentence: \n"); fgets(str,SIZE,stdin); printf("Enter a search word: \n"); fgets(searchString,SIZE,stdin); if (str1[strlen(str1) - 1] == '\n') { str1[strlen(str1)-1] = '\0'; } if (str[strlen(str) - 1] == '\n')...
c++ programming: Write a function called baseConverter(string number, int startBase, int endBase) in c++ which converts...
c++ programming: Write a function called baseConverter(string number, int startBase, int endBase) in c++ which converts any base(startBase) to another (endBase) by first converting the start base to decimal then to the end base. Do not use library. (bases 1-36 only)
2. [50] Write a C program to count the total number of commented characters and words...
2. [50] Write a C program to count the total number of commented characters and words in a C file taking both types of C file comments (single line and block) into account.
Write a C program that counts the number of odd numbers with using function count() within...
Write a C program that counts the number of odd numbers with using function count() within the set. The set has only one negative number which determines the end of set.
Q3)   Write a C program that counts the number of odd numbers with using function count()...
Q3)   Write a C program that counts the number of odd numbers with using function count() within the set. The set has only one negative number which determines the end of set.
C++ function to a string into enum function to a enum into a string check valid...
C++ function to a string into enum function to a enum into a string check valid / loop ( asking a couple of times until answer invaild) For example Enum Fruit ( APPLE, STRAWBERRY, BLUEBERRY, BLACKBERRY) output should be what is your favorit fruit? : strawberry you will have STRAWBERRY. what is your favorite fruite : peach invaild TIA
Python. Write a code that asks the user to enter a string. Count the number of...
Python. Write a code that asks the user to enter a string. Count the number of different vowels ( a, e, i, o, u) that are in the string and print out the total. You may need to write 5 different if statements, one for each vowel. Enter a string: mouse mouse has 3 different vowels
Given a string, such as x = ‘itm330’, write a Python program to count the number...
Given a string, such as x = ‘itm330’, write a Python program to count the number of digits and the number of letters in it. For example, in ‘itm330’, there are 3 letters and 3 digits. Hint: Very similar to page 11 on the slides. To check if a character c is a digit, use c.isdigit(). If c is a digit, c.isdigit() will be a True.
There is a C function decodeMorse(const String & string, char message[]). This function examines the binary...
There is a C function decodeMorse(const String & string, char message[]). This function examines the binary string and iteratively constructs a decimal value (val) and width of each binary pattern (separated by spaces), until a space or a null character ('\0') is encountered in the string. Once a space or a null character is found, this function should call the assembly code (decode_morse()) to obtain the corresponding ASCII value, for the current val and width, and place the ASCII value...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT