Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check for a specific count of letters in a row in a String Java

I want to check if my String contains words with a specific length

String s = "ab a abc ac";
if(s.contains(/*any words with 3 or more letters which would be 'abc'*/){
   //doSomething
}

Is there a way to do this in regex or with a simple method? Similar to

s.contains("[a-za-za-z]"); //or
s.contains().lettersInARow(3);

What I want is to find these and throw an Error when something longer than 2 characters is found

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

or with a simple method

String s = "😷ab a abc ac";
long countWordsWithAtLeastThreeCharacters = 
    Arrays.stream( s.split( " " ) )
    .filter( word -> input.codePoints().toArray().length > 3 )
    .count() ;

I added the FACE WITH MEDICAL MASK to demonstrate that this works with all characters. Avoid using char as it is physically incapable of representing most characters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading