Skip to content
Related Articles

Related Articles

Check if the given string is valid English word or not

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 01 Apr, 2022

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 lower case 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 <bits/stdc++.h>
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




<script>
    // JavaScript program to implement
    // the above approach
 
    // Function to find valid words
    const ValidWords = (sentence) => {
        let hyphen = 0;
        let size = sentence.length;
        if (sentence[0] >= 'A' && sentence[0] <= 'Z')
        {
            for (let i = 0; i < size; i++)
            {
                // Check for numbers
                if (sentence[i] >= '0' && sentence[i] <= '9')
                    return false;
                if (sentence[i] >= 'A' && sentence[i] <= 'Z')
                    return false;
 
                if (sentence[i] >= 'a' && sentence[i] <= 'z' ||
                sentence[i] >= 'A' && sentence[i] <= 'Z')
                    continue;
 
                if (sentence[i] == '-') {
                    // Only 1 hyphen is allowed
                    if (++hyphen > 1)
                        return false;
 
                    // hyphen should be surrounded
                    // by letters
                    if (i - 1 < 0
                        || !(sentence[i - 1] >= 'a' &&
                        sentence[i - 1] <= 'z' ||
                        sentence[i - 1] >= 'A' &&
                        sentence[i - 1] <= 'Z')
                        || i + 1 >= size
                        || !(sentence[i + 1] >= 'a' &&
                        sentence[i + 1] <= 'z' ||
                        sentence[i + 1] >= 'A' &&
                        sentence[i + 1] <= 'Z'))
                        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;
    }
 
    // Driver code
 
    let sentence = "i Love- Geeks-Forgeeks!";
 
    let word = sentence.split(' ');
    let ans = 0;
 
    for (let indx in word)
        if (ValidWords(word[indx]))
            ans++;
 
    // Display the result
    document.write(`${ans} words`);
 
    // This code is contributed by rakeshsahni
 
</script>

Output

1 words

 
 

 

Time Complexity: O(N) 
Auxiliary Space: O(N)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!