Open In App

Check if the given string is valid English word or not

Last Updated : 23 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 <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) 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 <iostream>
#include <string>
#include <cctype>
 
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");
    }
}


Python3




def is_valid_word(word):
    if not word:
        return False
 
    if not word[0].isalpha():
        return False
 
    hyphen_count = 0
 
    for i in range(1, len(word)):
        if word[i] == '-':
            hyphen_count += 1
 
            # Check hyphen conditions
            if hyphen_count > 1 or i == 1 or i == len(word) - 1 or not word[i - 1].isalpha() or not word[i + 1].isalpha():
                return False
        elif not word[i].islower():
            return False
 
    return True
 
def count_valid_words(sentence):
    count = 0
    word = ''
 
    for char in sentence:
        if char.isspace():
            if is_valid_word(word):
                count += 1
 
            word = ''
        else:
            word += char
 
    # Check the last word in the sentence
    if is_valid_word(word):
        count += 1
 
    return count
 
def main():
    sentence = "i Love- Geeks-Forgeeks!"
 
    valid_word_count = count_valid_words(sentence)
 
    print(f"{valid_word_count} words")
 
if __name__ == "__main__":
    main()


C#




using System;
 
class Program
{
    // Function to check if a word is valid based on specified criteria
    static bool IsValidWord(string word)
    {
        if (string.IsNullOrEmpty(word))
        {
            return false; // Empty string is not a valid word
        }
 
        if (!char.IsLetter(word[0]))
        {
            return false; // First character should be a letter
        }
 
        int hyphenCount = 0;
 
        for (int i = 1; i < word.Length; i++)
        {
            if (word[i] == '-')
            {
                hyphenCount++;
 
                // Criteria for valid hyphenated words
                if (hyphenCount > 1 || i == 1 || i == word.Length - 1 || !char.IsLetter(word[i - 1]) || !char.IsLetter(word[i + 1]))
                {
                    return false; // Invalid hyphenated word
                }
            }
            else if (!char.IsLower(word[i]))
            {
                return false; // Non-lowercase character found
            }
        }
 
        return true; // Word meets all criteria and is valid
    }
 
    // Function to count the number of valid words in a sentence
    static int CountValidWords(string sentence)
    {
        int count = 0;
        string word = "";
 
        for (int i = 0; i < sentence.Length; i++)
        {
            if (char.IsWhiteSpace(sentence[i]))
            {
                // Check if the word is valid and count it
                if (IsValidWord(word))
                {
                    count++;
                }
 
                word = ""; // Reset the word for the next iteration
            }
            else
            {
                word += sentence[i]; // Add characters to form a word
            }
        }
 
        // Check the last word in the sentence
        if (IsValidWord(word))
        {
            count++;
        }
 
        return count; // Return the count of valid words
    }
 
    // Entry point of the program
    static void Main()
    {
        string sentence = "i Love- Geeks-Forgeeks!";
 
        // Count the number of valid words in the given sentence
        int validWordCount = CountValidWords(sentence);
 
        Console.WriteLine(validWordCount + " words");
    }
}


Javascript




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");
    }
}
 
// code added by shinjanpatra


Output

1 words










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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads