Write a java program to find length of the largest Chunk in a string

Write a program to read a string and find the length of the largest chunk in the string. If there is no chunk print “No chunks” else print the length.

NOTE: chunk is the letter which is repeating 2 or more than 2 times.

The return type (Integer) should return the length of the largest chunk if the chunk is present, else return -1.

Input and Output Format

  • Input consists of a string.
  • Output consists of an integer value or a string value.

Refer sample output for formatting specifications

Sample Input 1:

You are toooo good

Sample Output 1:

4

(Because the largest chunk is the letter ‘o’ which is repeating 4 times)

Sample Input 2:

who are u

Sample Output 2:

No chunks

Find the length of the largest Chunk in a string in Java

Following are the steps to find the length of the largest chunk:

  • Input string from the user.
  • Declare and initialize variable max to 1 and b(to hold the length) to 0.
  • Create a string tokenizer to break strings into tokens.
  • Iterate over the tokens, and get each token in a string. Then, use for loop to traverse over this string and check every character in the token.
  • If they are the same, then increment the value of ‘n’.
  • Now, in order to print how many times the chunk of elements is repeated that check the value of n. If it is greater than max. Then transfer the value of n to the max and then add 1 to it and store it as variable b.
  • At last, print the value of b.
package com.demo2;

import java.util.Scanner;
import java.util.StringTokenizer;

public class LargestChunk {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
int max = 1;
int b = 0;
StringTokenizer t = new StringTokenizer(s1, " ");
while (t.hasMoreTokens()) {
String s2 = t.nextToken();
int n = 0;
for (int i = 0; i < s2.length() - 1; i++)
if (s2.charAt(i) == s2.charAt(i + 1))
n++;
if (n > max) {
max = n;
b = max + 1;
System.out.println(b);
}
}
if(b==0){
System.out.println("No chunks");
}

}
}

Output

Thus, in this way, we learn how to find the largest chunk of elements in a string.