Skip to content
Related Articles

Related Articles

Find the word from a given sentence having given word as prefix
  • Last Updated : 12 Oct, 2020

Given a string S representing a sentence and another string word, the task is to find the word from S which has the string word as a prefix. If no such word is present in the string, print -1.

Examples:

Input: S = “Welcome to Geeksforgeeks”, word=”Gee”
Output: Geeksforgeeks
Explanation:
The word “Geeksforgeeks” in the sentence has the prefix “Gee”.

Input: s=”Competitive Programming”, word=”kdflk”
Output: -1
Explanation:
No word in the string has “kdflk” as its prefix.

 

Approach: Follow the steps below to find which word has the given prefix:



  1. Extract the words from the sentence using the stringstream and store it in a vector of strings.
  2. Now, traverse the array and check which word contains the given word as its own prefix.
  3. If found to be true for any word, then print that word. Otherwise, if no such word is found, print -1.

Below is the implementation of the above approach:

C++




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

Java




// Java program for the above approach
import java.util.*;
import java.io.*;
import java.lang.Math;
 
class GFG{
      
// Function to find the position
// of the string having word as prefix
static String isPrefixOfWord(String sentence,
                             String Word)
{
    String a[] = sentence.split(" ");
   
    // Initialize an ArrayList
    ArrayList<String> v = new ArrayList<>();
     
    // Extract words from the sentence
    for(String e : a)
        v.add(e);
     
    // Traverse each word
    for(int i = 0; i < v.size(); i++)
    {
         
        // Traverse the characters of word
        for(int j = 0; j < v.get(i).length(); j++)
        {
             
            // If prefix does not match
            if (v.get(i).charAt(j) != Word.charAt(j))
                break;
                 
            // Otherwise
            else if (j == Word.length() - 1)
             
                // Return  the word
                return v.get(i);
        }
    }
     
    // Return -1 if not present
    return "-1";
}
 
// Driver code 
public static void main(final String[] args)
{
    String s = "Welcome to Geeksforgeeks";
    String word = "Gee";
   
    System.out.println(isPrefixOfWord(s, word));
}
}
 
// This code is contributed by bikram2001jha

Python3




# Python3 program for the
# above approach
 
# Function to find the
# position of the string
# having word as prefix
def isPrefixOfWord(sentence, word):
   
    a=sentence.split(" ")
 
    # Initialize an List
    v = []
 
    # Extract words from
    # the sentence
    for i in a:
        v.append(i)
 
    # Traverse each word
    for i in range(len(v)):
 
        # Traverse the characters of word
        for j in range(len(v[i])):
 
            # If prefix does not match
            if(v[i][j] != word[j]):
                break
 
            # Otherwise
            elif(j == len(word) - 1):
 
                # Return  the word
                return v[i]
 
    # Return -1 if not present
    return -1
 
# Driver code
s = "Welcome to Geeksforgeeks"
word = "Gee"
print(isPrefixOfWord(s, word))
 
# This code is contributed by avanitrachhadiya2155

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
      
// Function to find the position
// of the string having word as prefix
static String isPrefixOfWord(String sentence,
                             String Word)
{
  String []a = sentence.Split(' ');
 
  // Initialize an List
  List<String> v = new List<String>();
 
  // Extract words from the sentence
  foreach(String e in a)
    v.Add(e);
 
  // Traverse each word
  for(int i = 0; i < v.Count; i++)
  {
    // Traverse the characters of word
    for(int j = 0; j < v[i].Length; j++)
    {
      // If prefix does not match
      if (v[i][j] != Word[j])
        break;
 
      // Otherwise
      else if (j == Word.Length - 1)
 
        // Return  the word
        return v[i];
    }
  }
 
  // Return -1 if not present
  return "-1";
}
 
// Driver code 
public static void Main(String[] args)
{
  String s = "Welcome to Geeksforgeeks";
  String word = "Gee";
  Console.WriteLine(isPrefixOfWord(s, word));
}
}
 
// This code is contributed by Rajput-Ji
Output: 
Geeksforgeeks





 

Time Complexity: O(L), where L denotes the length of the string S 
Auxiliary Space: O(L)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :