How to count a specefic word in aparagraph using string ????

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Emi Mus
    New Member
    • Dec 2010
    • 1

    How to count a specefic word in aparagraph using string ????

    write a java program to count aword in aparagraph?
    ex: word "is" in "is name is the name is yours".
  • Sean Pedersen
    New Member
    • Dec 2010
    • 30

    #2
    Code:
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            String string = "is name is the name is yours";
            String match = "is";
            System.out.println(instancesOf(string, match));
        }
    
        static int instancesOf(final String string, final String match) {
            int ret = 0;
            final int stringlen = string.length();
            final int matchlen = match.length();
            for (int i = 0; i < stringlen - matchlen; i++) {
                if (string.substring(i, i + matchlen).contains(match)) {
                    ret++;
                }
            }
            return ret;
        }
    }
    The function doesn't care about spaces. it will match is in island.
    Last edited by Sean Pedersen; Dec 11 '10, 02:55 AM. Reason: more to say

    Comment

    Working...