java 实现统计某段文字在内容中出现的次数

本文演示如何使用Apache Commons Lang库中的StringUtils.countMatches方法来统计字符串中特定字符出现的次数,通过实例代码进行详细说明。
http://outofmemory.cn/code-snippet/815/java-zishutongji
一个api,位于apache.commons.lang.StringUtils类下的一个StringUtils.countMatches(paragraph, string);方法,这个方法返回值是一个数字
 
 
代码:

package cn.outofmemory;

import org.apache.commons.lang3.StringUtils;

public class WordCounter {

    public static void main(String[] args) {

        // String with our paragraph
        String paragraph = "Java Code Geeks (JCGs) is an independent online community focused on creating the"
        + "ultimate Java-to-Java developers resource center; targeted at the technical architect, technical"
        + "team lead (senior developer), project manager and junior developers alike. JCGs serve the Java, "
        + "Scala, Android, SOA, Agile and Telecom communities with daily news written by domain experts, "
        + "articles, tutorials, reviews, announcements, code snippets and open source projects.";

        // Declare the word you want to search
        String string = "Java";

        // Count word repetitions
        int counter = StringUtils.countMatches(paragraph, string);

        // Print the result
        System.out.println("Word <" + string + "> appeared " + counter + " times in the paragraph.");
    }
}

 
 
 

转载于:https://www.cnblogs.com/svennee/p/4082827.html

要在Java中编写一段代码,将由逗号分隔的符串中仅保留那些只出现一次的单词,并将其拼接起来,你可以按照以下步骤操作: ### 示例代码 ```java import java.util.*; public class UniqueString { public static String getUniqueWords(String input) { // 将输入符串按逗号分割成数组 String[] words = input.split(","); // 使用Map统计每个单词出现次数 Map<String, Integer> wordCount = new HashMap<>(); for (String word : words) { String trimmedWord = word.trim(); // 去除首尾空格 if (!trimmedWord.isEmpty()) { // 排除非空串 int count = wordCount.getOrDefault(trimmedWord, 0); wordCount.put(trimmedWord, count + 1); } } // 筛选出只出现过一次的单词并组成新的列表 List<String> uniqueWordsList = new ArrayList<>(); for (Map.Entry<String, Integer> entry : wordCount.entrySet()) { if (entry.getValue() == 1) { uniqueWordsList.add(entry.getKey()); } } // 把筛选后的单词用逗号连接返回 return String.join(",", uniqueWordsList); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入一串以逗号分隔的符串:"); String userInput = scanner.nextLine(); String result = getUniqueWords(userInput); System.out.println("处理后结果:" + result); } } ``` 上述程序首先会接收用户输入的一串以逗号作为分隔符的文字序列。通过`split()`函数根据指定符(这里是指逗号`,`)拆分为一个个独立元素存入数组;接着利用HashMap记录各个单词及其对应的频次信息;最后遍历这个哈希表找出所有值等于1的关键——即表示该关键在整个文本里唯一存在——并将它们再次组合成一个新的、只包含独一无二词汇的结果符串。 #### 输出示例: 假设我们有这样一个输入:“apple,banana,orange,apple,grape” 那么经过此段程序运行之后将会得到输出为“banana,orange,grape”。 请注意实际应用过程中需要考虑更多边界条件比如连续多个逗号之间无内容等情况,在上面提供的基础版本上可以进一步优化和完善功能细节。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值