package Others;import java.util.Scanner;/*** You enter a string into this program, and it will return how many words were* in that particular string** @author Marcus*/public class CountWords {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter your text: ");String str = input.nextLine();System.out.println("Your text has " + wordCount(str) + " word(s)");System.out.println("Your text has " + secondaryWordCount(str) + " word(s)");input.close();}private static int wordCount(String s) {if (s == null || s.isEmpty())return 0;return s.trim().split("[\\s]+").length;}/*** counts the number of words in a sentence but ignores all potential* non-alphanumeric characters that do not represent a word. runs in O(n) where* n is the length of s** @param s String: sentence with word(s)* @return int: number of words*/private static int secondaryWordCount(String s) {if (s == null || s.isEmpty())return 0;StringBuilder sb = new StringBuilder();for (char c : s.toCharArray()) {if (Character.isLetter(c) || Character.isDigit(c))sb.append(c);}s = sb.toString();return s.trim().split("[\\s]+").length;}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。