如何在Java中自定义方法统计字符串中指定字符的出现次数
实现count方法并通过指定JUnit测试
需求
实现一个静态方法count,统计字符串str中属于字符串chars的字符的出现次数,需通过以下JUnit测试用例:
JUnit测试用例
@Test public void test_count_bothEmptyString() { int expected = 0; int actual = CCStringsIfAndWhile.count("", ""); assertEquals("Testing count - both empty string", expected, actual); } @Test public void test_count_firstEmptyString() { int expected = 0; int actual = CCStringsIfAndWhile.count("", "abcdefghijklmnopqrstuvwxyz"); assertEquals("Testing count - first is empty string", expected, actual); } @Test public void test_count_secondEmptyString() { int expected = 0; int actual = CCStringsIfAndWhile.count("This is a test", ""); assertEquals("Testing count - second is empty string", expected, actual); } @Test public void test_count_one() { int expected = 1; int actual = CCStringsIfAndWhile.count("This is a test", "abc"); assertEquals("Testing count - 'This is a test', 'abc'", expected, actual); } @Test public void test_count_many() { int expected = 6; int actual = CCStringsIfAndWhile.count("This is a test", "sapqi"); assertEquals("Testing count - 'This is a test', 'sapqi'", expected, actual); } @Test public void test_count_upperAndLowerCase() { int expected = 7; int actual = CCStringsIfAndWhile.count("This is another test", "stpq"); assertEquals("Testing count - 'This is another test', 'stpq'", expected, actual); }
现有代码问题
你当前的代码存在几个关键错误:
- 循环内部的
return charCount++;会直接终止方法,导致无法遍历完整个字符串 - else分支将
charCount重置为0,会清空之前的统计结果,完全不符合需求 - 缺少判断字符是否属于
chars的核心条件
public static int count(String str, String chars) { int count = 0; int charCount = 0; while(count<str.length()) { if() { charCount++; return charCount++; } else { charCount=0; } count++; } return charCount; }
修正后的代码
public static int count(String str, String chars) { int charCount = 0; // 边界处理:任意一个字符串为空,直接返回0 if (str.isEmpty() || chars.isEmpty()) { return 0; } int index = 0; while (index < str.length()) { char currentChar = str.charAt(index); // 判断当前字符是否存在于chars中 if (chars.indexOf(currentChar) != -1) { charCount++; } index++; } return charCount; }
代码说明
- 边界处理:提前判断
str或chars为空的情况,直接返回0,满足前三个测试用例的要求 - 字符存在性判断:使用
chars.indexOf(currentChar) != -1检查当前字符是否在chars中(indexOf返回-1表示字符不存在) - 统计逻辑:遍历
str的每个字符,符合条件时累加计数,遍历完成后返回总次数
内容的提问来源于stack exchange,提问作者Hisham Souraya
相关产品推荐
相关产品推荐

