Find the word from a given sentence having given word as prefix | C ++ program for the above approach ; Function to find the position of the string having word as prefix ; Initialize a vector ; Extract words from the sentence ; Traverse each word ; Traverse the characters of word ; If prefix does not match ; Otherwise ; Return the word ; Return - 1 if not present ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string isPrefixOfWord ( string sentence , string Word ) { stringstream ss ( sentence ) ; vector < string > v ; string temp ; while ( ss >> temp ) { v . push_back ( temp ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { for ( int j = 0 ; j < v [ i ] . size ( ) ; j ++ ) { if ( v [ i ] [ j ] != Word [ j ] ) break ; else if ( j == Word . size ( ) - 1 ) return v [ i ] ; } } return " - 1" ; } int main ( ) { string s = " Welcome ▁ to ▁ Geeksforgeeks " ; string word = " Gee " ; cout << isPrefixOfWord ( s , word ) << endl ; return 0 ; }