How to count words in a string with punctuation in Java

1 Answer

0 votes
public class WordCounter {
    public static void main(String[] args) {
        String s = "python! ,,c, c++. c# $$$java@# php.";
        String[] words = s.split("\\s+");

        int count = 0;
        for (String word : words) {
            String cleaned = stripPunctuation(word);
            if (isAlphabetic(cleaned)) {
                count++;
            }
        }

        System.out.println(count);
    }

    // Removes punctuation from both ends of a word
    public static String stripPunctuation(String word) {
        int start = 0;
        int end = word.length();

        while (start < end && isPunctuation(word.charAt(start))) {
            start++;
        }
        while (end > start && isPunctuation(word.charAt(end - 1))) {
            end--;
        }

        return word.substring(start, end);
    }

    // Checks if a character is punctuation
    public static boolean isPunctuation(char c) {
        return "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".indexOf(c) >= 0;
    }

    // Checks if a string is alphabetic
    public static boolean isAlphabetic(String word) {
        return word.matches("[A-Za-z]+");
    }
}

 
 
 
/*
run:
 
6
 
*/

 



answered Nov 2, 2025 by avibootz
...