-3

I want to have a program that takes a string, splits it at a space, and prints the length of the smallest substring.

I wrote this but it just prints the length of the first string. What is my problem ?

Scanner input = new Scanner(System.in);
        String inp = input.nextLine();
        int counter = 0;
        String[]helper =new String[inp.length()];
        int minlength = Integer.MAX_VALUE;
        for (int i = 0; i < inp.length(); i++) 
        {
            if (inp.charAt(i) != ' ')
            {
                counter++;
                continue;
            }
            minlength = Math.min(counter, minlength);
            counter = 0;
        }
        System.out.println(minlength);
Bucket
  • 7,415
  • 9
  • 35
  • 45
Amin Ghasemi
  • 1,361
  • 2
  • 8
  • 7
  • 4
    What do you mean by *partite with space*? – Rohit Jain Oct 22 '13 at 17:39
  • partite means divided by and he wants to split at empty spaces. – But I'm Not A Wrapper Class Oct 22 '13 at 17:44
  • It's not clear what you are asking. Including few examples of input and expected result could help us understand what you mean. – Pshemo Oct 22 '13 at 17:46
  • 1
    it is not the first sub string's length , but is the second last substring legth that is getting printed. When you encounter space, print the length inside loop and default the length for last. Easy way is to use String Split features and print the lenght. – Jimmy Oct 22 '13 at 17:47

1 Answers1

0

Use .split method to split a string by spaces.

String[] stringArray = input.split("\\s+");

Generally you could do:

String[] stringArray = input.split(" ");

But this source explains why the first option is better: How do I split a string with any whitespace chars as delimiters?

Once you have the String[] stringArray, then you can loop through it and find the smallest length.

int minlength = Integer.MAX_VALUE;
for(int i = 0; i < stringArray.length; i++){
    if(stringArray[i].length() < minlength){
        minlength = stringArray[i].length();
    }
}
System.out.println(minlength);
Community
  • 1
  • 1