Ibrahim Ali
Ibrahim Ali

Reputation: 1297

Java 8 Stream, get string length due to several conditions

I have a program that calculate the occurrences of d, for example s = "dda" and n = 10 I will repeat those until I get s.length = 10 e.g ddaddaddad the result = 7d.

I have done this in basics loop:

int count = 0;
String s = "dda";
int n = 10;
for (int i = 0; i < s.length(); i++) {
     if (s.charAt(i) == 'd')
         count++;
}

for (int i = 0; i < n % s.length(); i++) {
     if (s.charAt(i) == 'd')
         count++;
}
return count * (n / s.length());

Thus I'm trying to do that using streams, and I'm wondering how I can do it?

What I already achieved:

return s.chars().filter(x -> x == 'd').count() * (n / s.length()) + (n % s.length());

I know The problem in that last part (n % s.length()) I need to check if the index contain d or not, but I don't know how to do that.

Upvotes: 1

Views: 1622

Answers (2)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

all you need to add to your calculation is to substring s by the reminder and repeat the count: -

    return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
            s.substring(0, n % s.length()).chars().filter(x -> x == 'd').count();

EDIT: if, for some reason, you dislike the oldfashined substring, you could replace it with stream of ints from 0 to the reminder:

    return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
            IntStream.range(0, n % s.length()).filter(i -> s.charAt(i)== 'd').count();

However, the question reminas whether this all-stream version is more comprehensive/readable.

Upvotes: 2

Naman
Naman

Reputation: 31878

You might just be looking for a simpler logic if I get your question right. It could be as :

private int characterCountWithRecurrenceWithinLimit(String string, int limit, char c) {
    // repeat string unless its shorter than the limit

    StringBuilder sBuilder = new StringBuilder(string);
    while (sBuilder.length() < limit) {
        sBuilder.append(string);
    }
    // keep the string within the limit
    String repeatedString = sBuilder.toString().substring(0, limit);
    // count the character occurrence
    return (int) IntStream.range(0, repeatedString.length())
            .filter(i -> repeatedString.charAt(i) == c)
            .count();
}

Upvotes: 0

Related Questions