(1)统计指定字符出现的次数
思路:逐个比较指定字符与字符串中各个字符进行比较即可。
(2)统计各个字符出现的次数
思路:
1:提取字符串str的首个字符,然后将整个字符串str中与首个字符相同的字符,全部替换为空字符串 "" ,得到新字符串tempStr,得到两个字符串的长度差即可。
2:利用hash-map的 key唯一特性,逐个将字符串str里的字符 put,遇到相同的key,将其value值 +1。
import java.util.HashMap;
import java.util.Map;
public class TestCountChar
{
public static void main(String [] args)
{
String str = "hello world";
String s = "o"; //统计字符o出现的次数
CountChar(str, s);
CountChar1(str);
CountChar2(str);
}
//统计字符串中指定字符出现的次数
public static void CountChar(String str, String s)
{
int count = 0;
for(int i=0; i<str.length(); i++)
{
//String.chatAt(i)返回的是字符,并非字符串
if(s.equals(String.valueOf(str.charAt(i))))
{
count++;
}
}
System.out.println("字符 "+s+" 出现了"+count+"次");
}
//统计字符串中每个字符出现的次数
public static void CountChar1(String str1)
{
int count = 0;
while(str1.length()>0)
{
String c =String.valueOf(str1.charAt(0)); //将第一个字符变成字符串c
String tempStr = str1.replaceAll(c, ""); //将字符串str1中,所有的字符串c 全都替换为空,原来的字符串长度将变短
count = str1.length() - tempStr.length();
str1 = tempStr; //将新字符串复制给str1,执行下一次循环
System.out.println(c +":"+count);
}
}
//统计字符串中每个字符出现的次数,利用hash-map的key唯一特性
public static void CountChar2(String str2)
{
Map<Character, Integer> map = new HashMap<>();
for(int i=0; i<str2.length(); i++)
{
char c = str2.charAt(i); //字符c
if(map.containsKey(c))
{
map.put(c, map.get(c) + 1); //如果已经存在,则 value值+1
}
else
{
map.put(c,1); //不存在,则放入的value值为1
}
}
System.out.println(map);
}
}
运行结果:
字符 o 出现了2次
h:1
e:1
l:3
o:2
:1
w:1
r:1
d:1
{ =1, r=1, d=1, e=1, w=1, h=1, l=3, o=2}