[Java] counts the number of each word in a string

Source: Internet
Author: User

This is a question from an electric plane. Word statistics is easy to think of using map to statistics, so think of using HashMap. But I did not think of splitting the word with split, thinking about the way to judge the space by traversing the characters. The interviewer said, what if there's more than one space between the words? In fact, the method of traversal is also possible, but it may be more difficult to deal with. There is nothing wrong, after all, I do not use the auxiliary space.

Since there is a simple way, you can use split to solve it. There may be multiple spaces between words, and using split will result in a space. The normal solution will then iterate through the array of saved words to remove the spaces in the array. We can use a regular expression in this.

Map<string, int[]> sumwords (String str) {if (str = = NULL) return NULL;STR = Str.trim (); int len = Str.length (); if (len = = 0) return null; map<string, int[]> map = new hashmap<string, int[]> ();//originally int[] can be replaced with an integer. However, when the integer is used, it automatically crates and unboxing, making                                                                        //using arrays of type int[] to improve efficiency, eliminating the process of type conversion string[] words = Str.split ("\\s+");// The regular expression takes one or more spaces as delimiters for (int i = 0; i < words.length; i++) {int[] counts = new Int[1];if (!map.containskey (words[i))) {Cou Nts[0] = 1;map.put (Words[i], counts);} else {counts[0]=map.get (words[i]) [0]+1;map.put (Words[i], counts);}} return map;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Java] counts the number of each word in a string

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.