java中字符串中取字符个数和数字个数,在线等

zgycsmb 2017-02-15 02:53:12
在一个java类中,想通过编写方法完成下面的功能

已知一个字符串 比如abc123
需要通过用集合的知识点完成
得到此字符串共有3个字母3个数字
尽量提供可运行的代码
在线等,多谢大家了
...全文
687 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

public static void main(String[] args) {
		String input="abc123";
		System.out.println(countNum("[a-zA-Z]", input));//字母个数
		System.out.println(countNum("\\d", input));//数字个数
		
	}
	/**
	 * 计算字符个数
	 * @param regex
	 * @param input
	 * @return
	 */
	public static int countNum(String regex,String input){
		Matcher m=Pattern.compile(regex).matcher(input);
		int count=0;
		while(m.find()){
			count++;
		}
		return count;
	}
乐之者v 2017-02-17
  • 打赏
  • 举报
回复
伸手党。。没意思。
bityourtail 2017-02-16
  • 打赏
  • 举报
回复
可运行通过,字母包含里大写和小写,若你只要小写,去掉||(c>='A'&&c<='Z')即可 public void depart(String s){ Set<Character> ans1 = new HashSet<Character>(); Set<Character> ans2 = new HashSet<Character>(); for(int i=0;i<s.length();i++){ char c = s.charAt(i); if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){ ans1.add(c); }else if(c>='0'&&c<='9'){ ans2.add(c); } } System.out.println("字母:"+ans1+", 数字: "+ans2); }
baidu_35973790 2017-02-15
  • 打赏
  • 举报
回复
public class test { public static void main(String[] args) { int numbercont=0; int charcont=0; String str= "abc123"; for(int i =0;i<str.length();i++){ if(Character.isDigit(str.charAt(i))){ numbercont++; } if(Character.isLetter(str.charAt(i))){ charcont++; } } System.out.println("数字:"+numbercont+"字母"+charcont); } }

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧