String Manipulation and Search

String Manipulation and Search

Make a program that:

A) Uses getline 2 times to get 2 string inputs from the user and use member functions and while loops to ask for the input untill they are not empty.

B) Looks for the second input inside of the first input, and prints where it is if it is found. Print that it is not found if it could not be found.

C) Use member functions to present how input1 would look if it didn't have input2 in it.

Answer

#include <iostream>
#include <string>

int main() {

    // A) Get inputs and ensure they're not empty
    std::string input1;
    do {
        std::cout << "Enter the first string: ";
        std::getline(std::cin, input1);
    } while (input1.empty());

	std::string input2;
    do {
        std::cout << "Enter the second string: ";
        std::getline(std::cin, input2);
    } while (input2.empty());

    // B) Find the second string in the first string
    size_t foundIndex = input1.find(input2);
    if (foundIndex != std::string::npos) {
        std::cout << "Second string found at index: " << foundIndex << std::endl;

    // C) Remove the second string from the first string
    std::string modifiedInput1 = input1;
    while ((foundIndex = modifiedInput1.find(input2)) != std::string::npos) {
        modifiedInput1.erase(foundIndex, input2.length());
    }
    std::cout << "First input without the second: " << modifiedInput1 << std::endl;
    } else {
        std::cout << "Second string not found in the first string." << std::endl;
    }
}

This program: A) uses do-while loops together with the std::string::empty method to ensure that the given inputs aren't empty.

B) Makes use of the std::string::find method to check if the second string is found inside the first string.

C) Uses the std::string::erase method with std::string::find to remove the second string from the first. This is done in a loop to remove all occurances of the second stirng.

Questions