Question

In: Computer Science

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')
{
str[strlen(str)-1] = '\0';
}
if (searchString[strlen(searchString) - 1] == '\n')
{
searchString[strlen(searchString)-1] = '\0';
}


printf("\n");

//Original string is contained in str

l1 = strlen(str);
l2 = strlen(searchString);

for(int i = 0; i < l1 - l2 +1; i++)
{

//Using strstr all the occurences are counted through iterating each successive location in the original string
if(strstr(str + i, searchString) == str + i)
{

//When search string is found in original string, count is increased and original string location to search is moved to the length of search string to find next occurences
count++;
i = i + l2 -1;
}
}

cout << "Found "<< count << " words of "<< searchString<<" in: \n" << str;

return 0;
}

=============================================================================

can someone explain to me what is going in in this loop i am so lost...The only thing i understand is the count++;

The part im having trouble understanding is why:

i < l1 - l2 +1   and also   strstr(str + i, searchString) == str + i (like why the '+ i')      and also why    i = i + l2 -1;

for(int i = 0; i < l1 - l2 +1; i++)
{
if(strstr(str + i, searchString) == str + i)
{
count++;
i = i + l2 -1;
}

Solutions

Expert Solution

I have included comments explaining each important statement in this program. Please find the commented program below. Go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Note: The given program is written terribly. There is a lot of bad programming practises followed and is a mixture of C and C++. I have explained everything as much as I can. I am not sure you could follow that easily, So I have written a modified version of this program at the bottom, which is way more efficient and easy to understand and is in pure C++ format. Have a look at it if you want.

#include <iostream>
#include <cstring>
#include <stdio.h>
#include <iostream>

using namespace std;

int main()
{
        
        //maximum size of input sentence
    const int SIZE = 40;
    //char array to store input sentence
    char str[SIZE];
    //there was no need for str1, so I removed it
    //char array to store search term
    char searchString[SIZE];
    int n;
    int l1, l2;
    int count = 0;
        
        //asking, reading input sentence
    printf("Enter a sentence: \n");
    fgets(str, SIZE, stdin);

        //asking, reading search term
    printf("Enter a search word: \n");
    fgets(searchString, SIZE, stdin);
        
        //if last character is a newline, replacing last char with null terminator ('\0')
        //so that the newline char is not considered for anything.
    if (str[strlen(str) - 1] == '\n') {
        str[strlen(str) - 1] = '\0';
    }
    //doing the same to searchString
    if (searchString[strlen(searchString) - 1] == '\n') {
        searchString[strlen(searchString) - 1] = '\0';
    }

    printf("\n");

        //finding length of input sentence
    l1 = strlen(str);
    //finding length of search term
    l2 = strlen(searchString);
        
        //looping from i = 0 to i = (l1 - l2)
        //we iterate until i = l1-l2 because we are searching for searchString in str
        //so we only need to traverse until the position in str where there could not be
        //any more occurrences of searchString possible
        //for example, if str is "abcdefh" and searchString is "abcd", we only need to
        //move i from 0 to length("abcdefh") minus length("abcd"), or 7-4 = 3, after index
        //3, it is guaranteed that there won't be another "abcd" possible, because the number
        //of characters left after index 3 is 3 ("efh") which is less than length of search 
        //string "abcd".
    for (int i = 0; i < l1 - l2 + 1; i++) {
                //strstr will search for a target string in a given string.
                //first parameter is the source string, second parameter is the string to be searched.
                //it returns the first position of the searchString if found, else NULL.
                //str is char array name, which is also pointer to the first position on the array
                //so str+i points to the position i values away from the beginning.
                //so if (strstr(str + i, searchString) returns the same position str+i, it means that
                //one occurrence of the target string starts at current position
        if (strstr(str + i, searchString) == str + i) {
                        //in that case we increment count
                        count++;
                        //advancing i l2 locations forward, to move into the next index after current 
                        //occurrence of searchString, to continue search
                        //subtracting 1 from i because the for loop will increment i after each loop
                        //which will ultimately make i=i+l2 (not a very good programming here)
            i = i + l2 - 1;
        }
    }
        //finally displaying the count
    cout << "Found " << count << " words of " << searchString << " in: \n" << str;
    return 0;
}

/*MODIFIED PROGRAM (DIFFERENT, YET EASY TO UNDERSTAND APPROACH)*/

#include <iostream>
#include <string>

using namespace std;

int main()
{
        //defining two string objects
        string sentence, searchString;
        
        //asking, reading sentence
        cout<<"Enter a sentence: \n";
        getline(cin, sentence);
        
        //and the search string
        cout<<"Enter search word: \n";
        getline(cin, searchString);
        
        //initializing count to 0
    int count=0;
    
    //we are using find method of string to search for a given string
    //if found, the method returns the position of first occurrence, if not
    //the method returns a value string::npos indicating the word is not found
    int pos=sentence.find(searchString);
    //we loop as long as pos is not string::npos
    while(pos!=string::npos){
        //incrementing count
        count++;
        //now we find next position of searchString if there's any
        //find method can also take a second parameter which tells the system to
        //search for a given string after that position. so here we search for
        //searchString after pos+searchString.length() position
        pos=sentence.find(searchString, pos+searchString.length());
        }
        
        //displaying count
    cout << "Found " << count << " words of " << searchString << " in: \n" << sentence;
    return 0;
}

/*OUTPUT*/

Enter a sentence:
some text containing some occurrences of the word 'some'
Enter search word:
some
Found 3 words of some in:
some text containing some occurrences of the word 'some'

Related Solutions

Write a Python program to count occurrences of items (and retrieve the most 3 or least...
Write a Python program to count occurrences of items (and retrieve the most 3 or least 3 words). Write a Python program to sort a dictionary by keys or values in ascending or descending order by 2 methods.
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
Write a program that inputs a string that represents a binary number. The string can contain...
Write a program that inputs a string that represents a binary number. The string can contain only 0s and 1s and no other characters, not even spaces. Validate that the entered number meets these requirements. If it does not, display an error message. If it is a valid binary number, determine the number of 1s that it contains. If it has exactly two 1s, display "Accepted". Otherwise, display "Rejected". All input and output should be from the console. Examples of...
Q. Given a document with 32 distinct characters, with equal number of occurrences of each, what...
Q. Given a document with 32 distinct characters, with equal number of occurrences of each, what would be the ratio of the length of the Huffman coded document to the original, if each character in the input was coded in 8 bits? Show your analysis.
2.c++ if and loop statement Write a program that will count the number of even number...
2.c++ if and loop statement Write a program that will count the number of even number and odd numbers between two inputted numbers. Display the numbers and compute the sum and average of all the even numbers and the sum and average all the odd numbers. Sample outputs: Enter starting number:3 Enter starting number:4 Enter ending number:10 Enter ending number:10 odd numbers Even number 3 4 5 6 7 8 9 10 number of even numbers=4 number of even numbers=4...
In java please Question: You are given a string s. Your task is to count the...
In java please Question: You are given a string s. Your task is to count the number of ways of splitting s into three non-empty parts a, b and c (s = a + b + c) in such a way that a + b, b + c and c + a are all different strings. For s = "xzxzx", the output should be countWaysToSplit(s) = 5. Consider all the ways to split s into three non-empty parts:
In C++ For this assignment, you will write a program to count the number of times...
In C++ For this assignment, you will write a program to count the number of times the words in an input text file occur. The WordCount Structure Define a C++ struct called WordCount that contains the following data members: An array of 31 characters named word An integer named count Functions Write the following functions: int main(int argc, char* argv[]) This function should declare an array of 200 WordCount objects and an integer numWords to track the number of array...
Write a Java program that takes in a string and a number and prints back the...
Write a Java program that takes in a string and a number and prints back the string from the number repeatedly until the first character... for example Pasadena and 4 will print PasaPasPaP. Ask the user for the string and a number Print back the string from the number repeatedly until the first character For both programs please utilize: methods arrays loops Turn in screenshots
IN PYTHON Given a string with duplicate characters in it. Write a program to generate a...
IN PYTHON Given a string with duplicate characters in it. Write a program to generate a list that only contains the duplicate characters. In other words, your new list should contain the characters which appear more than once. Suggested Approach Used two nested for loops. The first for loop iterates from 0 to range(len(input_str)). The second for loop iterates from first_loop_index + 1 to range(len(input_str)). The reason you want to start at first_loop_index + 1 in the nested inner loop...
Given two ArrayLists of Strings (ArrayList<String>), write a Java method to return the higher count of...
Given two ArrayLists of Strings (ArrayList<String>), write a Java method to return the higher count of the characters in each ArrayList.  For example, if list1 has strings (“cat, “dog”, “boat”, “elephant”) and list 2 has strings (“bat”, “mat”, “port”, “stigma”), you will return the value 18.  The list 1 has 18 characters in total for all its strings combined and list2 has 16 characters for all of its strings combined.  The higher value is 18. If the character count is the same, you...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT