Open In App

# Check if the given string is valid English word or not

Given string str, the task is to check if this string str consists of valid English words or not.

A string is known as a valid English word if it meets all the below criteria-

• The string can have an uppercase character as the first character only.
• The string can only have lowercase characters.
• The string can consist of only one hyphen(‘-‘) surrounded by characters on both ends.
• The string cannot consist of any digits.
• If there is any punctuation mark it must be only one and it must be present at the end.

Print the number of valid words in the string str.

Input: str = “i Love- Geeks-forgeeks!”
Output: 1 word
Explanation:
word 1 = “i” does not contain first uppercase character, it is not valid word
word 2 = “Love-” hyphen is not surrounded by characters on both ends, it is not valid word
word 3 = “Geeks-forgeeks!” is a valid word

Input: str = “!this  1-s b8d!”
Output: 0 words
Explanation:
word 1 = “!this” punctuation mark is in the beginning, it is not valid word
word 2 = “1-s” digit as first character, it is not valid word
word 3 = “b8d!” first character is not uppercase, it is not valid word

Approach:

• Initialize the variable ans to keep count of the number of valid words.
• Loop through each word present in the sentence.
• Check each letter of the word to see if it meets the criteria mentioned in the problem statement.
• If any of the criteria is not met then return false.
• If all the criteria are satisfied by the word, then increment the value of the variable ans.
• Print the value of the variable ans.

Below is the C++ program of the above approach-

## C++

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Function to find valid words``bool` `ValidWords(string sentence)``{``    ``int` `hyphen = 0;``    ``int` `size = sentence.size();``    ``if` `(``isupper``(sentence[0])) {``        ``for` `(``int` `i = 0; i < size; i++) {``            ``// Check for numbers``            ``if` `(``isdigit``(sentence[i]))``                ``return` `false``;``            ``if` `(``isupper``(sentence[i]))``                ``return` `false``;` `            ``if` `(``isalpha``(sentence[i]))``                ``continue``;` `            ``if` `(sentence[i] == ``'-'``) {``                ``// Only 1 hyphen is allowed``                ``if` `(++hyphen > 1)``                    ``return` `false``;` `                ``// hyphen should be surrounded``                ``// by letters``                ``if` `(i - 1 < 0``                    ``|| !``isalpha``(sentence[i - 1])``                    ``|| i + 1 >= size``                    ``|| !``isalpha``(sentence[i + 1]))``                    ``return` `false``;``            ``}` `            ``// Punctuation must be at the``            ``// end of the word``            ``else` `if` `(i != size - 1``                     ``&& ispunct(sentence[i]))``                ``return` `false``;``        ``}``    ``}``    ``else``        ``return` `true``;``}` `// Driver code``int` `main()``{``    ``string sentence = ``"i Love- Geeks-Forgeeks!"``;` `    ``istringstream s(sentence);``    ``string word;``    ``int` `ans = 0;` `    ``while` `(s >> word)``        ``if` `(ValidWords(word))``            ``ans++;` `    ``// Display the result``    ``cout << ans << ``" words"``;``}`

## Java

 `/*package whatever //do not write package name here */` `import` `java.io.*;` `class` `GFG {` `    ``// Function to find valid words``    ``static` `boolean` `ValidWords(String sentence)``    ``{``        ``int` `hyphen = ``0``;``        ``int` `size = sentence.length();``        ``if` `(Character.isUpperCase(sentence.charAt(``0``))) {``            ``for` `(``int` `i = ``0``; i < size; i++) {``                ``// Check for numbers``                ``if` `(Character.isDigit(sentence.charAt(i)))``                    ``return` `false``;``                ``if` `(Character.isUpperCase(``                        ``sentence.charAt(i)))``                    ``return` `false``;` `                ``if` `(Character.isAlphabetic(``                        ``sentence.charAt(i)))``                    ``continue``;` `                ``if` `(sentence.charAt(i) == ``'-'``) {``                    ``// Only 1 hyphen is allowed``                   ``hyphen = hyphen +``1` `;``                    ``if` `(hyphen > ``1``)``                        ``return` `false``;` `                    ``// hyphen should be surrounded``                    ``// by letters``                    ``if` `(i - ``1` `< ``0``                        ``|| !Character.isAlphabetic(``                            ``sentence.charAt(i - ``1``))``                        ``|| i + ``1` `>= size``                        ``|| !Character.isAlphabetic(``                            ``sentence.charAt(i + ``1``)))``                        ``return` `false``;``                ``}` `                ``// Punctuation must be at the``                ``// end of the word``                ``else` `if` `(i != size - ``1``                         ``&& ((sentence.charAt(i) == ``'!'``                              ``|| sentence.charAt(i) == ``','``                              ``|| sentence.charAt(i) == ``';'``                              ``|| sentence.charAt(i) == ``'.'``                              ``|| sentence.charAt(i) == ``'?'``                              ``|| sentence.charAt(i) == ``'-'``                              ``|| sentence.charAt(i) == ``'\''``                              ``|| sentence.charAt(i) == ``'\"'``                              ``|| sentence.charAt(i)``                                     ``== ``':'``)))``                    ``return` `false``;``            ``}``        ``}``        ``else``            ``return` `true``;``      ``return` `false``;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``String sentence = ``"i Love- Geeks-Forgeeks!"``;``        ``int` `ans = ``0``;``        ``String words[] = sentence.split(``" "``);``        ``for` `(String word : words) {``            ``if` `(ValidWords(word)==``true``){``                ``ans++;``            ``}``        ``}` `        ``// Display the result``        ``System.out.print(ans + ``" words"``);``    ``}``}`

## Python3

 `# Python program to implement``# the above approach` `# Function to find valid words``def` `ValidWords(sentence):``    ``hyphen ``=` `0``    ``size ``=` `len``(sentence)``    ``if` `(sentence[``0``] >``=` `'A'` `and` `sentence[``0``] <``=` `'Z'``):``        ``for` `i ``in` `range``(size):``          ` `            ``# Check for numbers``            ``if` `(sentence[i] >``=` `'0'` `and` `sentence[i] <``=` `'9'``):``                ``return` `False``            ``if` `(sentence[i] >``=` `'A'` `and` `sentence[i] <``=` `'Z'``):``                ``return` `False``            ``if` `(sentence[i] >``=` `'a'` `and` `sentence[i] <``=` `'z'` `or` `sentence[i] >``=` `'A'``                ``and` `sentence[i] <``=` `'Z'``):``                ``continue``            ``if` `(sentence[i] ``=``=` `'-'``):``              ` `                ``# Only 1 hyphen is allowed``                ``if` `(hyphen``+``1` `> ``1``):``                    ``return` `False``                  ` `                ``# hyphen should be surrounded``                ``# by letters``                ``if` `(i ``-` `1` `< ``0` `or` `~(sentence[i ``-` `1``] >``=` `'a'` `and``                    ``sentence[i ``-` `1``] <``=` `'z'` `or` `sentence[i ``-` `1``] >``=` `'A'``                    ``and` `sentence[i ``-` `1``] <``=` `'Z'``) ``or` `i ``+` `1` `>``=` `size ``or``                    ``~(sentence[i ``+` `1``] >``=` `'a'` `and` `sentence[i ``+` `1``] <``=` `'z'``                      ``or` `sentence[i ``+` `1``] >``=` `'A'` `and` `sentence[i ``+` `1``] <``=` `'Z'``)):``                    ``return` `False` `            ``# Punctuation must be at the``            ``# end of the word``            ``elif` `(i !``=` `size ``-` `1` `and` `((sentence[i] ``=``=` `'!'` `or` `sentence[i] ``=``=` `','``                   ``or` `sentence[i] ``=``=` `';'` `or` `sentence[i] ``=``=` `'.'` `or` `sentence[i] ``=``=` `'?'``                   ``or` `sentence[i] ``=``=` `'-'` `or` `sentence[i] ``=``=` `'\''``or` `sentence[i] ``=``=` `'\"'``                   ``or` `sentence[i] ``=``=` `':'``))):``                ``return` `False``    ``else``:``        ``return` `True` `# Driver code``sentence ``=` `"i Love- Geeks-Forgeeks!"` `word ``=` `sentence.split(``' '``)``ans ``=` `0` `for` `indx ``in` `word :``    ``if` `(ValidWords(indx)):``        ``ans ``+``=` `1` `# Display the result``print``(f``"{ans} words"``)` `# This code is contributed by shinjanpatra`

## C#

 `/*package whatever //do not write package name here */``using` `System;` `class` `GFG``{` `  ``// Function to find valid words``  ``static` `bool` `ValidWords(String sentence)``  ``{``    ``int` `hyphen = 0;``    ``int` `size = sentence.Length;``    ``if` `(``char``.IsUpper(sentence[0]))``    ``{``      ``for` `(``int` `i = 0; i < size; i++)``      ``{``        ` `        ``// Check for numbers``        ``if` `(``char``.IsDigit(sentence[i]))``          ``return` `false``;``        ``if` `(``char``.IsUpper(sentence[i]))``          ``return` `false``;` `        ``if` `(``char``.IsLetter(sentence[i]))``          ``continue``;` `        ``if` `(sentence[i] == ``'-'``)``        ``{``          ` `          ``// Only 1 hyphen is allowed``          ``hyphen = hyphen + 1;``          ``if` `(hyphen > 1)``            ``return` `false``;` `          ``// hyphen should be surrounded``          ``// by letters``          ``if` `(i - 1 < 0``              ``|| !``char``.IsLetter(sentence[i - 1])``              ``|| i + 1 >= size``              ``|| !``char``.IsLetter(sentence[i + 1]))``            ``return` `false``;``        ``}` `        ``// Punctuation must be at the``        ``// end of the word``        ``else` `if` `(i != size - 1``                 ``&& ((sentence[i] == ``'!'``                      ``|| sentence[i] == ``','``                      ``|| sentence[i] == ``';'``                      ``|| sentence[i] == ``'.'``                      ``|| sentence[i] == ``'?'``                      ``|| sentence[i] == ``'-'``                      ``|| sentence[i] == ``'\''``                      ``|| sentence[i] == ``'\"'``                      ``|| sentence[i]``                      ``== ``':'``)))``          ``return` `false``;``      ``}``    ``}``    ``else``      ``return` `true``;``    ``return` `false``;``  ``}` `  ``// Driver code``  ``public` `static` `void` `Main()``  ``{``    ``String sentence = ``"i Love- Geeks-Forgeeks!"``;``    ``int` `ans = 0;``    ``String[] words = sentence.Split(``" "``);``    ``foreach` `(String word ``in` `words)``    ``{``      ``if` `(ValidWords(word) == ``true``)``      ``{``        ``ans++;``      ``}``    ``}` `    ``// Display the result``    ``Console.Write(ans + ``" words"``);``  ``}``}` `// This code is contributed by gfgking.`

## Javascript

 ``

Output

```1 words

```

Time Complexity: O(N) as only one traversal of the string of length N is enough for the algorithm to perform all the tasks hence the overall complexity is linear.
Auxiliary Space: O(N) as the variable s stores all the words of the strings hence the overall space occupied by the algorithm is equal to the length of the string

Approach 2:

Here is another approach to check for valid words in a given sentence:

• Split the sentence into words using whitespace as a delimiter.
• For each word, iterate over its characters and perform the following checks:
• The first character should be an uppercase or lowercase letter.
• All other characters should be lowercase letters or hyphens.
• There should be at most one hyphen, and it should not be the first or last character.
• There should be no digits or punctuation marks.
• If a word passes all the checks, increment a counter to keep track of the number of valid words.

After processing all the words in the sentence, display the number of valid words found.
Here is an implementation of this approach in C++:

## C++

 `#include ``#include ``#include ` `using` `namespace` `std;` `bool` `isValidWord(``const` `string& word) {``    ``if` `(word.empty()) {``        ``return` `false``;``    ``}` `    ``if` `(!``isalpha``(word[0])) {``        ``return` `false``;``    ``}` `    ``int` `hyphenCount = 0;` `    ``for` `(``int` `i = 1; i < word.length(); i++) {``        ``if` `(word[i] == ``'-'``) {``            ``hyphenCount++;` `            ``if` `(hyphenCount > 1 || i == 1 || i == word.length() - 1 || !``isalpha``(word[i - 1]) || !``isalpha``(word[i + 1])) {``                ``return` `false``;``            ``}``        ``}``        ``else` `if` `(!``islower``(word[i])) {``            ``return` `false``;``        ``}``    ``}` `    ``return` `true``;``}` `int` `countValidWords(``const` `string& sentence) {``    ``int` `count = 0;``    ``string word;` `    ``for` `(``int` `i = 0; i < sentence.length(); i++) {``        ``if` `(``isspace``(sentence[i])) {``            ``if` `(isValidWord(word)) {``                ``count++;``            ``}` `            ``word.clear();``        ``}``        ``else` `{``            ``word += sentence[i];``        ``}``    ``}` `    ``if` `(isValidWord(word)) {``        ``count++;``    ``}` `    ``return` `count;``}` `int` `main() {``    ``string sentence = ``"i Love- Geeks-Forgeeks!"``;` `    ``int` `validWordCount = countValidWords(sentence);` `    ``cout << validWordCount << ``" words"` `<< endl;` `    ``return` `0;``}`

## Java

 `import` `java.util.*;` `public` `class` `ValidWordsCount {` `    ``// Function to check if a given word is valid``    ``public` `static` `boolean` `isValidWord(String word) {``        ``if` `(word.isEmpty()) {``            ``return` `false``;``        ``}` `        ``// Check if the first character is a letter``        ``if` `(!Character.isLetter(word.charAt(``0``))) {``            ``return` `false``;``        ``}` `        ``int` `hyphenCount = ``0``;` `        ``// Loop through the characters of the word starting from the second character``        ``for` `(``int` `i = ``1``; i < word.length(); i++) {``            ``if` `(word.charAt(i) == ``'-'``) {``                ``hyphenCount++;` `                ``// Conditions to check if hyphen placement is valid``                ``if` `(hyphenCount > ``1` `|| i == ``1` `|| i == word.length() - ``1` `|| !Character.isLetter(word.charAt(i - ``1``)) || !Character.isLetter(word.charAt(i + ``1``))) {``                    ``// If there is more than one hyphen, if it's at the beginning or end of the word, or if the characters around the hyphen are not letters, the word is invalid.``                    ``return` `false``;``                ``}``            ``} ``else` `if` `(!Character.isLowerCase(word.charAt(i))) {``                ``// If a non-lowercase letter is found (other than a hyphen), the word is invalid.``                ``return` `false``;``            ``}``        ``}` `        ``// If all conditions pass, the word is valid.``        ``return` `true``;``    ``}` `    ``// Function to count the number of valid words in a sentence``    ``public` `static` `int` `countValidWords(String sentence) {``        ``int` `count = ``0``;``        ``String word = ``""``;` `        ``// Loop through the characters of the sentence``        ``for` `(``int` `i = ``0``; i < sentence.length(); i++) {``            ``if` `(Character.isWhitespace(sentence.charAt(i))) {``                ``// If a whitespace character is encountered, check if the current word is valid and increment the count if it is.``                ``if` `(isValidWord(word)) {``                    ``count++;``                ``}` `                ``// Reset the word variable for the next word``                ``word = ``""``;``            ``} ``else` `{``                ``// If a non-whitespace character is encountered, append it to the current word.``                ``word += sentence.charAt(i);``            ``}``        ``}` `        ``// After the loop, check the last word in the sentence and increment the count if it is valid.``        ``if` `(isValidWord(word)) {``            ``count++;``        ``}` `        ``// Return the total count of valid words in the sentence.``        ``return` `count;``    ``}` `    ``public` `static` `void` `main(String[] args) {``        ``// Input sentence``        ``String sentence = ``"i Love- Geeks-Forgeeks!"``;` `        ``// Call the function to count the number of valid words in the sentence``        ``int` `validWordCount = countValidWords(sentence);` `        ``// Print the result``        ``System.out.println(validWordCount + ``" words"``);``    ``}``}`

Output

```1 words

```

Time Complexity: O(N) where N is the of length of string.
Auxiliary Space: O(1) for constant time taken