Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to find the length of the shortest word in a string with Java

2 Answers

0 votes
public class Program {
    public static void main(String args[]) {
        String s = "Java is object oriented programming language";    
        String[] words = s.split(" ");
 
        int shorLength = words[0].length();

        for (int i = 1; i < words.length; i++) {
            if (words[i].length() < shorLength) {
                shorLength = words[i].length();
            }
        }
        System.out.println(shorLength);
    }
}
 
 
 
 
/*
run:
   
2
   
*/

 



answered Sep 17, 2021 by avibootz
edited 13 hours ago by avibootz
0 votes
public class ShortestWord {

    // Returns the length of the shortest word in the string
    public static int shortestWordLength(String text) {
        if (text == null || text.isEmpty()) {
            return 0;
        }

        // Split on whitespace (spaces, tabs, newlines)
        String[] words = text.trim().split("\\s+");

        int minLen = Integer.MAX_VALUE;

        for (String word : words) {
            int len = word.length();
            if (len < minLen) {
                minLen = len;
            }
        }

        return minLen == Integer.MAX_VALUE ? 0 : minLen;
    }

    public static void main(String[] args) {
        String text = "Find the shortest word length in this string";

        int result = shortestWordLength(text);

        System.out.println("Shortest word length: " + result);
    }
}

  
  
/*
run:
  
Shortest word length: 2
  
*/

 



answered 9 hours ago by avibootz
...