You can use the indexOf(String s,int i)
method in the String class. In this method, s is a string div, and i is searched starting from the i subscript. The position of this string in the calling string, the return value is of type int.
Recommended related learning videos: java video tutorials
Examples are as follows:
//创建方法ciShu,返回int计算s2在字符串s1中出现的次数; public static int ciShu(String s1,String s2){ //定义一个int变量,用来计算s2在s1中出现的次数; int he = 0; //遍历s1 for(int i = 0;i<s1.length();i++){ //调用方法indexOf,计算s2在s1字符串中出现的下标, int t = s1.indexOf(s2,i); //当用if判断,当遍历开始下标i与s2在s1中出现的下标位置相等时变量he自增1; if(i==t){ he++; } //返回he的值就是s2在s1中出现的次数; return he; }
java Related article tutorial recommendations: java programming getting Started
The above is the detailed content of How to determine how many specified characters a string contains in java. For more information, please follow other related articles on the PHP Chinese website!