java text2
时间:2010-10-16 来源:大眼儿
public class Count
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串:");
String str = sc.nextLine();
System.out.println("请输入指定字符串:");
String st = sc.nextLine();
int n = 0;
for (int i = 0; i <= str.length() - st.length(); i++)
{
if (str.substring(i,i+st.length()).equals(st))
{
n++;
i = i+st.length()-1;
}
}
System.out.println("指定字符串出现次数:" + n);
}
}
indexOf()方法:
import java.util.Scanner;
public class Count2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串:");
String str = sc.nextLine();
System.out.println("请输入指定字符串:");
String st = sc.nextLine();
int n = 0, i = 0;
while (i < str.length() - st.length() + 1)
{
i = str.indexOf(st, i) + st.length();
n++;
}
System.out.println("指定字符串出现次数:" + n);
}
}