Search code examples
javastringsplitsubstringcontains

Java split string to get only two words


I have a Java string like "hello world bye moon" and I'm looking for an efficient way to extract the first two words from it. Currently, I'm using the split method and then concatenating the first two elements of the resulting array. However, I'm wondering if there's a more concise and efficient way to achieve this.

Here's my current code:

public class ExtractFirstTwoWords {
    public static void main(String[] args) {
        String inputString = "hello world bye moon";

        // Split the string into words
        String[] words = inputString.split(" ");

        // Check if there are at least two words
        if (words.length >= 2) {
            // Extract the first two words
            String firstTwoWords = words[0] + " " + words[1];
            System.out.println("First two words: " + firstTwoWords);
        } else {
            System.out.println("The input string does not contain at least two words.");
        }
    }
}

Is there a built-in Java method or a more efficient approach to extract the first two words from a string without splitting and concatenating all the words in the string?


Solution

  • In Java, you can achieve this more efficiently and concisely without splitting and concatenating by using the StringTokenizer class or regular expressions. Here's an example using StringTokenizer:

    import java.util.StringTokenizer;
    
    public class ExtractFirstTwoWords {
        public static void main(String[] args) {
            String inputString = "hello world bye moon";
    
            // Use StringTokenizer to split the string into words
            StringTokenizer tokenizer = new StringTokenizer(inputString);
    
            // Check if there are at least two words
            if (tokenizer.countTokens() >= 2) {
                // Extract the first two words
                String firstTwoWords = tokenizer.nextToken() + " " + tokenizer.nextToken();
                System.out.println("First two words: " + firstTwoWords);
            } else {
                System.out.println("The input string does not contain at least two words.");
            }
        }
    }
    

    Alternatively, you can use regular expressions for a more powerful and flexible approach:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class ExtractFirstTwoWords {
        public static void main(String[] args) {
            String inputString = "hello world bye moon";
    
            // Define a regular expression to match words
            Pattern pattern = Pattern.compile("\\b\\w+\\b");
    
            // Create a Matcher
            Matcher matcher = pattern.matcher(inputString);
    
            // Find the first two words
            StringBuilder firstTwoWords = new StringBuilder();
            for (int i = 0; i < 2 && matcher.find(); i++) {
                firstTwoWords.append(matcher.group()).append(" ");
            }
    
            if (firstTwoWords.length() > 0) {
                // Remove the trailing space
                firstTwoWords.setLength(firstTwoWords.length() - 1);
                System.out.println("First two words: " + firstTwoWords.toString());
            } else {
                System.out.println("The input string does not contain at least two words.");
            }
        }
    }
    

    Both of these approaches avoid creating an intermediate array and are more efficient for extracting the first two words from a string.