1 Star 0 Fork 82

zscgrhg/Java

forked from 编程语言算法集/Java 
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
CountWords.java 1.26 KB
一键复制 编辑 原始数据 按行查看 历史
github-actions 提交于 2020-10-24 18:23 +08:00 . Formatted with Google Java Formatter
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;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/frostforest/Java.git
git@gitee.com:frostforest/Java.git
frostforest
Java
Java
master

搜索帮助