以下程序的功能是,使用String类中的indexOf()方法统计一个字符串在另一个字符串中的出现次数.

例如字符串"this"在字符串"this is my first program. this…

public class Java1
{
public staticvoid main(String[] args)
{
Stringstr1="this";
Stringstr2="this is my first program. this...";
intcount=0,len1,len2;
len1=str1.length();
len2=str2.length();
/**********************************/
for(inti=0;i?len2-len1;i++)
{
/**********************************/
intj=str2.?;
if(j==i)
/**********************************/
?;
}
System.out.println(count);

}
}


public static void main(String[] args) {

  String str1="this";

      String str2="this is my first program. this...";

      int count=0,len1,len2;

      len1=str1.length();

      len2=str2.length();

   /**********************************/

      for(int i=0;i<len2-len1;i++)

      {

   /**********************************/

          int j=str2.indexOf(str1,i);

          if(j==i)

   /**********************************/

           count++;

      }

      System.out.println(count);


}

温馨提示:内容为网友见解,仅供参考
第1个回答  2015-06-04
public class IndexOfTest {

 public static void main(String[] args) {
  String a ="abcabc23423abc342334abc34534abc23423";
  String b="abc"; 
  System.out.println(getSubNum(a,b));
 }
 public static int getSubNum(String a,String b){
  int num=0;
  String str=a;
  int index=a.indexOf(b);
  while(index!=-1){
   num++;
   str=str.substring(index+b.length()-1);
   index=str.indexOf(b);
  }
  return num;
 }

}

第2个回答  2015-06-04
什么问题?追问

以下程序的功能是,使用String类中的indexOf()方法统计一个字符串在另一个字符串中的出现次数。例如字符串“this”在字符串“thisis my first program. this…”中出现了2次。请将程序补充完整。
注意:请勿改动程序已有内容,仅在?处填入适当的语句。

追答package com.jbit.test1;

public class Java1 {
public static void main(String[] args) {
String str1 = "this";
String str2 = "this is my first program. this...";
int count = 0, len1, len2;
len1 = str1.length();
len2 = str2.length();
/**********************************/
for (int i = 0; i <= len2 - len1; i++) {
/**********************************/
int j = str2.indexOf("this");
if (j == i) {
/**********************************/
count++;
str2 = str2.substring(str1.length() + j);
i = 0;
len2 = str2.length();
}
}
System.out.println(count);

}
}

这样就可以了

相似回答