Dada una oración como una string str y una palabra palabra , la tarea es verificar si la palabra está presente en str o no. Una oración es una string compuesta de varias palabras y cada palabra está separada por espacios.
Ejemplos:
Entrada: str = «Geeks for Geeks», word = «Geeks»
Salida: Word está presente en la oraciónEntrada: str = «Geeks for Geeks», word = «eeks»
Salida: Word no está presente en la oración
Enfoque: en este algoritmo, se usa stringstream para dividir la oración en palabras y luego comparar cada palabra individual de la oración con la palabra dada. Si se encuentra la palabra, la función devuelve verdadero.
Tenga en cuenta que esta implementación no busca una subsecuencia o substring, solo busca una sola palabra completa en una oración.
A continuación se muestra la implementación del enfoque de búsqueda que distingue entre mayúsculas y minúsculas:
CPP
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function that returns true if the word is found bool isWordPresent(string sentence, string word) { // To break the sentence in words stringstream s(sentence); // To temporarily store each individual word string temp; while (s >> temp) { // Comparing the current word // with the word to be searched if (temp.compare(word) == 0) { return true; } } return false; } // Driver code int main() { string s = "Geeks for Geeks"; string word = "Geeks"; if (isWordPresent(s, word)) cout << "Yes"; else cout << "No"; return 0; }
Java
// Java implementation of the approach class GFG { // Function that returns true if the word is found static boolean isWordPresent(String sentence, String word) { // To break the sentence in words String []s = sentence.split(" "); // To temporarily store each individual word for ( String temp :s) { // Comparing the current word // with the word to be searched if (temp.compareTo(word) == 0) { return true; } } return false; } // Driver code public static void main(String[] args) { String s = "Geeks for Geeks"; String word = "Geeks"; if (isWordPresent(s, word)) System.out.print("Yes"); else System.out.print("No"); } } // This code is contributed by PrinciRaj1992
Python
# Python3 implementation of the approach # Function that returns true if the word is found def isWordPresent(sentence, word): # To break the sentence in words s = sentence.split(" ") for i in s: # Comparing the current word # with the word to be searched if (i == word): return True return False # Driver code s = "Geeks for Geeks" word = "Geeks" if (isWordPresent(s, word)): print("Yes") else: print("No") # This code is contributed by mohit kumar 29
C#
// C# implementation of the approach using System; class GFG { // Function that returns true if the word is found static bool isWordPresent(String sentence, String word) { // To break the sentence in words String []s = sentence.Split(' '); // To temporarily store each individual word foreach(String temp in s) { // Comparing the current word // with the word to be searched if (temp.CompareTo(word) == 0) { return true; } } return false; } // Driver code public static void Main(String[] args) { String s = "Geeks for Geeks"; String word = "Geeks"; if (isWordPresent(s, word)) Console.Write("Yes"); else Console.Write("No"); } } // This code is contributed by 29AjayKumar
Javascript
<script> // JavaScript implementation of the approach // Function that returns true if the word is found function isWordPresent(sentence, word) { // To break the sentence in words let s = sentence.split(" "); // To temporarily store each individual word for ( let temp=0;temp<s.length;temp++) { // Comparing the current word // with the word to be searched if (s[temp] == (word) ) { return true; } } return false; } // Driver code let s = "Geeks for Geeks"; let word = "Geeks"; if (isWordPresent(s, word)) document.write("Yes"); else document.write("No"); // This code is contributed by patel2127 </script>
Yes
Complejidad temporal: O(n) donde n es la longitud de la oración.
Espacio auxiliar: O(n) donde n es la longitud de la string.
A continuación se muestra la implementación del enfoque de búsqueda que no distingue entre mayúsculas y minúsculas:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function that returns true if the word is found bool isWordPresent(string sentence, string word) { // To convert the word in uppercase transform(word.begin(), word.end(), word.begin(), ::toupper); // To convert the complete sentence in uppercase transform(sentence.begin(), sentence.end(), sentence.begin(), ::toupper); // Both strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words stringstream s(sentence); // To store the individual words of the sentence string temp; while (s >> temp) { // Compare the current word // with the word to be searched if (temp.compare(word) == 0) { return true; } } return false; } // Driver code int main() { string s = "Geeks for Geeks"; string word = "geeks"; if (isWordPresent(s, word)) cout << "Yes"; else cout << "No"; return 0; }
Java
// Java implementation of the approach import java.util.*; class GFG { // Function that returns true if the word is found static boolean isWordPresent(String sentence, String word) { // To convert the word in uppercase word = transform(word); // To convert the complete sentence in uppercase sentence = transform(sentence); // Both Strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words String []s = sentence.split(" "); // To store the individual words of the sentence for ( String temp :s) { // Comparing the current word // with the word to be searched if (temp.compareTo(word) == 0) { return true; } } return false; } static String transform(String word) { return word.toUpperCase(); } // Driver code public static void main(String[] args) { String s = "Geeks for Geeks"; String word = "geeks"; if (isWordPresent(s, word)) System.out.print("Yes"); else System.out.print("No"); } } // This code is contributed by PrinciRaj1992
Python3
# Python3 implementation of the approach # Function that returns true if the word is found def isWordPresent(sentence, word) : # To convert the word in uppercase word = word.upper() # To convert the complete sentence in uppercase sentence = sentence.upper() # Both strings are converted to the same case, # so that the search is not case-sensitive # To break the sentence in words s = sentence.split(); for temp in s : # Compare the current word # with the word to be searched if (temp == word) : return True; return False; # Driver code if __name__ == "__main__" : s = "Geeks for Geeks"; word = "geeks"; if (isWordPresent(s, word)) : print("Yes"); else : print("No"); # This code is contributed by AnkitRai01
C#
// C# implementation of the approach using System; class GFG { // Function that returns true if the word is found static bool isWordPresent(String sentence, String word) { // To convert the word in uppercase word = transform(word); // To convert the complete sentence in uppercase sentence = transform(sentence); // Both Strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words String []s = sentence.Split(' '); // To store the individual words of the sentence foreach ( String temp in s) { // Comparing the current word // with the word to be searched if (temp.CompareTo(word) == 0) { return true; } } return false; } static String transform(String word) { return word.ToUpper(); } // Driver code public static void Main(String[] args) { String s = "Geeks for Geeks"; String word = "geeks"; if (isWordPresent(s, word)) Console.Write("Yes"); else Console.Write("No"); } } // This code is contributed by 29AjayKumar
Javascript
<script> // Javascript implementation of the approach // Function that returns true if the word is found function isWordPresent(sentence,word) { // To convert the word in uppercase word = transform(word); // To convert the complete sentence in uppercase sentence = transform(sentence); // Both Strings are converted to the same case, // so that the search is not case-sensitive // To break the sentence in words let s = sentence.split(" "); // To store the individual words of the sentence for ( let temp=0;temp<s.length;temp++) { // Comparing the current word // with the word to be searched if (s[temp] == (word)) { return true; } } return false; } function transform(word) { return word.toUpperCase(); } // Driver code let s = "Geeks for Geeks"; let word = "geeks"; if (isWordPresent(s, word)) document.write("Yes"); else document.write("No"); // This code is contributed by unknown2108 </script>
Yes
Complejidad temporal: O(longitud(es))
Espacio auxiliar: O(1)
Método n.º 3: Uso de las funciones integradas de Python:
- Como todas las palabras en una oración están separadas por espacios.
- Tenemos que dividir la oración por espacios usando split().
- Dividimos todas las palabras por espacios y las almacenamos en una lista.
- Usamos la función count() para verificar si la palabra está en la array
- Si el valor de la cuenta es mayor que 0, la palabra está presente en la string
A continuación se muestra la implementación:
Python3
# Python3 implementation of the approach # Function that returns true # if the word is found def isWordPresent(sentence, word): # To convert the word in uppercase word = word.upper() # To convert the complete # sentence in uppercase sentence = sentence.upper() # splitting the sentence to list lis = sentence.split() # checking if word is present if(lis.count(word) > 0): return True else: return False # Driver code s = "Geeks for Geeks" word = "geeks" if (isWordPresent(s, word)): print("Yes") else: print("No") # This code is contributed by vikkycirus
Javascript
<script> // JavaScript implementation of the approach // Function that returns true // if the word is found function isWordPresent(sentence, word){ // To convert the word in uppercase word = word.toUpperCase() // To convert the complete // sentence in uppercase sentence = sentence.toUpperCase() // splitting the sentence to list let lis = sentence.split(' ') // checking if word is present if(lis.indexOf(word) != -1) return true else return false } // Driver code let s = "Geeks for Geeks" let word = "geeks" if (isWordPresent(s, word)) document.write("Yes","</br>") else document.write("No","</br>") // This code is contributed by shinjanpatra </script>
Producción:
Yes
Complejidad temporal: O(longitud(es))
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por DeveshRattan y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA