当前位置: 移动技术网 > IT编程>开发语言>Java > Java的字符串中对子字符串的查找方法总结

Java的字符串中对子字符串的查找方法总结

2019年07月22日  | 移动技术网IT编程  | 我要评论
java中字符串中子串的查找共有四种方法,如下: 1、int indexof(string str) :返回第一次出现的指定子字符串在此字符串中的索引。 2、int

java中字符串中子串的查找共有四种方法,如下:
1、int indexof(string str) :返回第一次出现的指定子字符串在此字符串中的索引。
2、int indexof(string str, int startindex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。
3、int lastindexof(string str) :返回在此字符串中最右边出现的指定子字符串的索引。
4、int lastindexof(string str, int startindex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。

indexof()用法说明

indexof()

返回 string 对象内第一次出现子字符串的字符位置。

string.indexof(substring[, startindex])

参数

string

必选项。string 对象或文字。

substring 必选项。

要在 string 对象中查找的子字符串。

starindex 可选项。

该整数值指出在 string 对象内开始查找的索引。如果省略,则从字符串的开始处查找。

说明
indexof 方法返回一个整数值,指出 string 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。

如果 startindex 是负数,则 startindex 被当作零。如果它比最大的字符位置索引还大,则它被当作最大的可能索引。

从左向右执行查找。否则,该方法与 lastindexof 相同。

示例
下面的示例说明了 indexof 方法的用法。

function indexdemo(str2){ 
var str1 = "babebibobubabebibobu" 
var s = str1.indexof(str2); 
return(s); 
}

java查找字符串中的包含子字符串的个数
1.用indexof的方法:

public class test11 
{

 private static int counter = 0;
 /**
 * @param args
 */
 public static void main(string[] args) 
 {
 string str ="sdss**&hgjhadhcasch& ^^";
 int i = stringnumbers(str);
 system.out.println(i);
 }
 
 public static int stringnumbers(string str)
 {
 if (str.indexof("java")==-1)
 {
 return 0;
 }
 else if(str.indexof("java") != -1)
 {
 counter++;
 stringnumbers(str.substring(str.indexof("java")+4));
 return counter;
 }
 return 0;
 }
}

2.如果子字符串不是一个首尾相同的字符串,还可以这样实现:

if(str.indexof("java") != -1)
 {
 string[] str1 = str.split("java");
 system.out.println(str1.length-1);
 }
 else 
 {
 system.out.println(0);
 }

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网