day08-常用类-String-的获取方法练习
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
package com.inmind.string01;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/*
|
||||
|
||||
2.字符串查找。 【scanner indexOf 不停地找,直到找不到为止(死循环) index+1找】
|
||||
键盘录入一个大字符串,再录入一个小字符串。
|
||||
统计小字符串在大字符串中出现的次数。
|
||||
*/
|
||||
public class Test06 {
|
||||
public static void main(String[] args) {
|
||||
//键盘录入一个大字符串,再录入一个小字符串。
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("请输入一个长字符串:");
|
||||
String longStr = sc.nextLine();
|
||||
System.out.println("请输入一个短字符串:");
|
||||
String shortStr = sc.nextLine();
|
||||
int count = getCount(longStr, shortStr);
|
||||
System.out.println("小字符串在大字符串中出现的次数为:"+count);
|
||||
}
|
||||
|
||||
//统计小字符串在大字符串中出现的次数。
|
||||
public static int getCount(String longStr, String shortStr) {
|
||||
int count = 0;//统计出现的次数
|
||||
|
||||
//public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引,如果找不到是-1
|
||||
//分析:也就是indexOf方法,查找shortStr,返回-1就是找不到了,就结束查询了
|
||||
int index = 0;//记录每次查找子字符串的索引,便于下一次查找(循环条件的参数)
|
||||
/*while (index != -1) {
|
||||
index = longStr.indexOf(shortStr,index);
|
||||
if (index != -1) {
|
||||
//下一次查找就得从index+1开始
|
||||
index++;
|
||||
count++;
|
||||
}
|
||||
}*/
|
||||
|
||||
while ((index = longStr.indexOf(shortStr,index)) != -1) {//将index的赋值与判断放在一起同时作为循环条件
|
||||
//下一次查找就得从index+1开始
|
||||
index++;
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user