[Java] 纯文本查看 复制代码
package com.itheima.homework;
import java.util.Scanner;
/*1.键盘录入一个大字符串,再录入一个小字符串
2.统计小字符串在大字符串中出现的次数
3.代码运行打印格式:
请输入大字符串:javajava I love java l like jajavava I enjoy javajavajava
请输入小字符串:heima
控制台输出:小字符串heima,在大字符串woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma中共出现3次*/
public class HomeWork02 {
public static void main(String[] args) {
//创建键盘录入
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个大字符串:");
String s1 = sc.nextLine();
System.out.println("请输入一个小字符串:");
String s2 = sc.nextLine();
int count = 0;
for (int i = 0; i <= s1.length()-s2.length(); i++) {
String s3 = s1.substring(i,s2.length() + i);
if (s2.equals(s3)) {
count++;
}
}
System.out.println("小字符串" + s2 + ",在大字符串" + s1 + "中共出现" + count + "次");
}
}
[Java] 纯文本查看 复制代码
package com.itheima.tests;
import java.util.Scanner;
/*1.键盘录入一个大字符串,再录入一个小字符串
2.统计小字符串在大字符串中出现的次数
3.代码运行打印格式:
请输入大字符串:javajava I love java l like jajavava I enjoy javajavajava
请输入小字符串:heima
控制台输出:小字符串heima,在大字符串woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma中共出现3次
*/
public class Test03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入大字符串:");
String l = sc.nextLine();
System.out.println("请输入小字符串:");
String s = sc.nextLine();
int count = getCount(l, s);
System.out.println(count);
}
//遍历大字符,
public static int getCount(String l, String s) {
int count = 0;
int index = 0;
while ((index = l.indexOf(s)) != -1) {
count++;
l = l.substring(index + 1);
}
return count;
}
}