首页 > 学院 > 开发设计 > 正文

统计某个字符串出现的次数或者是否存在

2019-11-08 18:30:10
字体:
来源:转载
供稿:网友

统计某个字符串出现的次数

判断testStr字符串或者字符testChar是否存在目标字符串中targetStr

package sun.rain.amazing;import org.apache.commons.lang3.StringUtils;import org.junit.Test;/** * 统计某个字符串出现的次数 * 判断testStr字符串或者字符testChar是否存在目标字符串中targetStr * @author sunRainAmazing * */public class StringApPRanceCount { public static String STRING ="i am a student . hello world , day day up , good good study !"; public static String STR = "good"; /** * 采用Apache下的工具类才进行测试 */ @Test public void getCount(){ System.out.println(StringUtils.countMatches(STRING, STR)); } /** * 采用String内部的长度来进行测试 */ @Test public void testLength(){ int firstLength = STRING.length(); int lastLength = STRING.replace(STR, "").length(); int count = (firstLength-lastLength)/3; System.out.println("出现的次数"+count); System.out.println("出现的次数"+(STRING.length()-STRING.replace(STR, "").length())/3); } /** * 判断是否存在某个字符串内容 * indexOf() ---若不存在返回 -1 */ @Test public void isExists(){ if(STRING.indexOf(STR) != -1){ System.out.println("存在"); } System.out.println(STRING.indexOf(STR) != -1? STR+"存在"+STRING:STR+"不存在"+STRING); }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表