Takacs Takacs - 1 year ago 83
Java Question

counting specific characters in string

I'm new at coding. If anyone can help me out: looking for a solution at this code, how to count how many times the "END" can be found at the randomly generated string.

Thank you guys!

public class Tombos {

public static void main (String[] args) throws FileNotFoundException {

PrintStream out1 = System.out;
PrintStream out2 = new PrintStream(new File("out.txt"));

int i;
for (i=0; i<1000; i++) {
char random = betuk.charAt((int)(26*Math.random()));
Scanner beolvas = new Scanner(new File("out.txt"));
String x = beolvas.next();
if (x.contains("END")) {
out1.print( "tartalmaz"); // include "END"
} else {
out1.print( "nem tartlmaz"); // not include "END"

Answer Source

In case you are a user of Apache Commons library, StringUtils#countMatches would do the job.

int count = StringUtils.countMatches(x, "END");

If not, I would probably use String#split

int count = x.split("END").length - 1;

It's a little bit ugly but it's easy and it's an one-liner:)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download