Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- // This program searches a text for a text string and
- // Surrounds all occurrences of the text string with brackets.
- // The number of occurrences is counted, and a number for
- // each occurrence is included with the opening bracket.
- /* Test text
- Estimates of the age of the Moon range from 4.5 Ga to significantly younger. A leading hypothesis is that it was formed by accretion from material loosed from Earth after a Mars-sized object with about 10% of Earth's mass, named Theia, collided with Earth. It hit Earth with a glancing blow and some of its mass merged with Earth. Between approximately 4.1 and 3.8 Ga, numerous asteroid impacts during the Late Heavy Bombardment caused significant changes to the greater surface environment of the Moon and, by inference, to that of Earth.*/
- int main()
- {
- string text; // The text to search.
- string word; // The word to look for.
- string opening_bracket; // The opening bracket in front of the found word.
- string opening_bracket_start = "{"; // Part of the opening bracket in front of the found word.
- string closing_bracket = "}}"; // The closing bracket after the found word.
- size_t position = 0; // Location of a found word.
- int position_count = 0; // Number of words found.
- cout << "This program will count the number of times a \n"
- "string of characters appears in a text and show where it is.\n";
- cout << "\nEnter your text:";
- cout << endl; // Go to the next line.
- getline(cin, text); // Get the text to search.
- cout << "\nEnter word to search for: ";
- getline(cin, word); // Get the word to search for.
- position = text.find(word, 0); // Find the word.
- while (position != string::npos) // While there is more text to search,
- {
- position_count++; // Count the found word.
- opening_bracket = opening_bracket_start + to_string(position_count) + opening_bracket_start; // Create the opening bracket.
- text.insert(position, opening_bracket); // Insert the opening bracket.
- text.insert(position + opening_bracket.size() + word.size(), closing_bracket); // Insert the closing bracket.
- position = text.find(word, position + opening_bracket.size() + word.size() + closing_bracket.size()); // Find the next occurrence of the word.
- }
- // If the word did not appear in the text, inform the user.
- if (position_count == 0) cout << "The word \"" << word << "\" does not appear in the text.\n";
- else // Otherwise, if the word appeared in the text,
- {
- // State how many times the word appeared.
- cout << "The word \"" << word << "\" appears " << position_count << " time" << ((position_count > 1) ? "s" : "") << " in the text: \n";
- // Display the text with the found word in brackets.
- cout << '\n' << text << endl;
- }
- return 0; // End the program.
- }
Add Comment
Please, Sign In to add comment