java char 计算_Java如何计算字符串中char出现的次数?

本示例说明如何计算字符串中字符出现的次数。我们展示了两种方法,使用String.replaceAll(String regex, String replace)方法和创建一个循环,以检查String中的每个字符并计算匹配的字符。package org.nhooo.example.lang;

public class CharCounter {

public static void main(String[] args) {

String text = "a,b,c,c,e,f,g,g,g,g,h";

// 使用CharCounter.countCharOccurrences()方法进行计数。

int numberOfLetterC = CharCounter.countCharOccurrences(text, 'c');

System.out.println("Letter c = " + numberOfLetterC);

//其他解决方案是使用String.replaceAll()方法。

// 我们将用空字符串替换除计数字符以外的其他字符。

// 为了得到出现的字符,我们计算剩余的长度

// 字符串。

int numberOfComma = text.replaceAll("[^,]", "").length();

System.out.println("Comma    = " + numberOfComma);

int numberOfLetterG = text.replaceAll("[^g]", "").length();

System.out.println("Letter g = " + numberOfLetterG);

}

/**

* 计算指定字符在字符串中出现的次数。

*/

private static int countCharOccurrences(String source, char target) {

int counter = 0;

// 循环遍历字符串,如果

// 在字符串中找到目标字符。

for (int i = 0; i 

if (source.charAt(i) == target) {

counter++;

}

}

return counter;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值