This example will determine how to count the number of digits contained within a string using java, java 8 and Google guava . Each snippet below will check if a string is a number then increment a counter validating that there are 4 numbers using junit assertEquals .
Straight up Java @Test
public void digits_in_string_guava_java () {
String phrase = "Creating xml using java gives me heart burn, "
+ "hopefully java 8, java 9, java 10 address this" ;
int numberOfDigits = 0 ;
char [] checkForNumbers = phrase . toCharArray ();
for ( char val : checkForNumbers ) {
if ( Character . isDigit ( val )) {
numberOfDigits ++;
}
}
assertEquals ( 4 , numberOfDigits );
}
Java 8 @Test
public void digits_in_string_guava_java8 () {
String phrase = "Creating xml using java gives me heart burn, "
+ "hopefully java 8, java 9, java 10 address this" ;
assertEquals ( 4 , phrase . chars (). filter ( Character: : isDigit ). count ());
}
Google Guava @Test
public void digits_in_string_guava () {
String phrase = "Creating xml using java gives me heart burn, "
+ "hopefully java 8, java 9, java 10 address this" ;
String numberOfDigits = CharMatcher . DIGIT . retainFrom ( phrase );
assertEquals ( 4 , numberOfDigits . length ());
}
Count occurrences of digit in string posted by Justin Musgrove on 04 November 2014
Tagged: java and java-string
Share on: Facebook Google+
All the code on this page is available on github:
CountOccurrencesOfDigit.java