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,987 questions

51,931 answers

573 users

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
...