String str = "The party has been divided abs14 on! the issue, with moderates5789 concerned about the effects on the most vulnerable."; String[] words = str.split("\\s+"); System.out.println(Arrays.toString(words)); 

I break a line into an array of words on a space. And then it is necessary to somehow set the condition that if the word does not contain special characters and numbers, then it will be added to the variable count . Tell me how to do it correctly, without using regex. Need to create another array char ?

    2 answers 2

    If without using regular expressions, then you can simply head on:

     public class Main { public static void main(String[] args) { String str = "The party has been divided abs14 on! the issue, with moderates5789 concerned about the effects on the most vulnerable."; String[] words = str.split("\\s+"); int count = 0; for (String word : words) { if (isValidWord(word)) { count++; } } System.out.println("Count: " + count); } private static boolean isValidWord(String word) { char[] chars = word.toCharArray(); for (char c : chars) { if (!Character.isAlphabetic(c)) { return false; } } return true; } } 

    UPD :

    Manual check on the belonging of the Latin character:

     private static boolean isLatinChar(char c) { return (c >= 65 && c <= 90) || (c >= 97 && c <= 122); } 

    Where:

    • 65 - character code A ;
    • 90 - character code Z ;
    • 97 - character code a ;
    • 122 is the character code z .

    When comparing, an implicit conversion from char to int occurs.

    • Is it possible to solve this problem without using the condition (! Character.isAlphabetic (c))? Or rather, replace it with something more understandable for a beginner to learn a programming language. I understand that each character has its own code in the ascii table. How to write a condition in this case? Thanks in advance for your help. - YuriiS
    • @YuriiS, Added. - post_zeew
    • @YuriiS is not only ASCII (this is the last century), but Unicode and a character can have more than one code. - Mikhail Vaysman

    Here is an option to do everything in one line.

     String str = "The party has been divided abs14 on! the issue, with moderates5789 concerned about the effects on the most vulnerable."; long count = Pattern.compile("\\s+").splitAsStream(str) .map(w -> w.chars().allMatch(Character::isAlphabetic)) .filter(c -> c) .count(); System.out.println("Count: " + count); 
    • Thank you for your answer, but we have not yet passed the Pattern. For me, this is not clear yet))) - YuriiS
    • I think you also have not passed the stream yet, but it may help someone else. - Mikhail Vaysman