Home >Java >JavaBase >How to determine how many specified characters a string contains in java

How to determine how many specified characters a string contains in java

王林
王林Original
2019-11-26 16:56:1012478browse

How to determine how many specified characters a string contains in java

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn