Home  >  Article  >  Backend Development  >  Find words prefixed with a given word from a given sentence

Find words prefixed with a given word from a given sentence

WBOY
WBOYforward
2023-08-27 20:09:11764browse

Find words prefixed with a given word from a given sentence

When dealing with natural language processing or text analysis, you often need to search for a specific word or phrase within a larger body of text. A common task is to find all words in a sentence that start with a given prefix. In this article, we'll explore how to use C to accomplish this task.

algorithm

  • Read the input sentences and prefixes.

  • Break the input sentence into individual words.

  • For each word in the sentence, check if it starts with the given prefix.

  • If a word starts with this prefix, it is added to the matching word list.

  • Print matching word list.

Example

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
   string sentence, prefix;
   vector<string> words;
   
   // Read in the input sentence and prefix
   sentence="The quick brown fox jumps over the lazy dog";
   prefix="fox";
   
   // Tokenize the input sentence into individual words
   string word = "";
   for (auto c : sentence) {
      if (c == ' ') {
         words.push_back(word);
         word = "";
      }
      else {
         word += c;
      }
   }
   words.push_back(word);

   // Find all words in the sentence that start with the given prefix
   vector<string> matches;
   for (auto w : words) {
      if (w.substr(0, prefix.length()) == prefix) {
         matches.push_back(w);
      }
   }
   
   // Print the list of matching words
   cout << "Matching words:" << endl;
   for (auto m : matches) {
      cout << m << endl;
   }
   
   return 0;
}

Output

Matching words:
fox

Test case example

Suppose we have the following input sentence:

The quick brown fox jumps over the lazy dog

We want to find all words starting with the prefix "fox". Running this input using the above code will produce the following output:

In this example, the only word in the sentence that begins with the prefix "fox" is "fox" itself, so it is the only word printed as a match.

in conclusion

In natural language processing and text analysis, finding all words starting with a given prefix in a sentence is a useful task. We can easily accomplish this task using C by tokenizing the input sentence into individual words and checking whether each word matches a prefix.

The above is the detailed content of Find words prefixed with a given word from a given sentence. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete