查找Java String中出现的字符 [英] Find occurrences of characters in a Java String

查看:289
本文介绍了查找Java String中出现的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算字符串中字符的出现次数,假设我有字符串aaaab,我如何计算其中的数量?

I would like to count the occurrences of a character in a string, suppose I have the string "aaaab", how would i count the amount of a's in it?

推荐答案

如果不使用正则表达式,代码看起来更容易阅读。

The code looks way easier to read if you don't use regular expressions.

int count = 0;
for(int i =0; i < string.length(); i++)
    if(string.charAt(i) == 'a')
        count++;

count 现在包含'a'的数量在你的字符串中。并且,这在最佳时间内执行。

count now contains the number of 'a's in your string. And, this performs in optimal time.

正则表达式适用于模式匹配。但只需一个常规循环即可完成工作。

Regular expressions are nice for pattern matching. But just a regular loop will get the job done here.

这篇关于查找Java String中出现的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆