关于字符串统计次数

这些东西自己写感觉很简单的东西,可是面试的时候一紧张就说不出来了。。。

package testcherry;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BB {
public static void main(String[] args)
{
countEveryNum();
}

private static void countNum()
{
Pattern p = Pattern.compile("[0-9]");
Matcher m = null;
String str = "abc123456789defg";
//统计数字出现的次数
int count = 0;
for(int i=0;i<str.length();i++)
{
m = p.matcher(String.valueOf(str.charAt(i)));
if(m.find())
{
count ++;
}

}
System.out.println("count:"+count);
}

private static void countEveryNum()
{
Pattern p = Pattern.compile("[0-9]");
Matcher m = null;
String str = "abc1234555567898defg";
Map map = new HashMap();
//统计数字出现的次数
int count = 0;
int k=1;
for(int i=0;i<str.length();i++)
{
m = p.matcher(String.valueOf(str.charAt(i)));

if(m.find())
{
if(map.containsKey(str.charAt(i)))
{
int value_key = (Integer) map.get(str.charAt(i));
int old = map.size();
map.put(str.charAt(i),value_key);
int new_count = map.size();
if(new_count == old)
{
map.put(str.charAt(i),value_key+=1);
}
}
else
{
map.put(str.charAt(i),1);
}

}

}
System.out.println("map:"+map.entrySet());
}
}

猜你喜欢

转载自www.cnblogs.com/zssw1990/p/9182598.html
今日推荐