Most text editors have a word search function. This feature allows for quickly locating a specific word within a document. Some editors can also count the number of times a particular word appears in the document.
Now, please program the following functionality: Given a word, output the number of times it appears and its first occurrence position in a given text. Note that when matching the word, case should not be considered (case insensitive), but the match must be exact. This means the provided word must match exactly with a standalone word in the text without considering the case (see Example 1). If the provided word is only a part of a word in the text, it should not count as a match (see Example 2).
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
EOF inputs: There are 2 lines per test case. The first line is a string containing only letters, representing a given word. The second line is a string that may contain letters and spaces only, representing the given text or article. | There is only one line of input. If the given word is found in the article, output two integers separated by a space. These integers represent the number of times the word appears in the article and the position of its first occurrence (the position of the word's first letter in the article, starting from 0). If the word does not appear in the article, output the integer -1 directly. |
To to be or not to be is a question to Did the Ottoman Empire lose its power at that time | 2 0 -1 |
Thought Process
All strings should be converted to either lowercase or uppercase when collecting data.
Using a for loop to tokenize a string, instead of using stringstream, because the latter would ignore consecutive spaces.
When you receive a string, you want to determine if it matches the target string you're searching for. If it does, you need to check if it's the first occurrence. You can declare a boolean variable to keep track of this and increment your answer accordingly.
Sample Code-ZeroJudge A308: Counting Words
#include <iostream>
#include <vector>
using namespace std;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
string target;
while (getline(cin, target)) {
for (int i = 0; i<target.length(); i++) target[i] = tolower(target[i]);
string str, tmp = "";
getline(cin, str);
bool first = true;
int begin = 0, count = 0;
for (int i = 0; i<str.length(); i++) {
if (str[i] == ' ' && !tmp.empty()) {
if (tmp == target) {
if (first) {
first = false;
begin = i-target.length();
}
count++;
}
tmp = "";
continue;
}
if (str[i] != ' ') tmp += tolower(str[i]);
}
if (count == 0) cout << "-1\n";
else cout << count << " " << begin << "\n";
}
}
//ZeroJudge A308
//Dr. SeanXD