【Java作业】2017.10.28 / 10.29

来源:互联网 发布:js点击按钮旋转图片 编辑:程序博客网 时间:2024/06/07 23:00
/*统计大串中小串出现的次数例如:"yuhellortyuhellosad"中"hello"出现了两次*//*分析:1.使用String类中的indexOf(String str)方法,返回小串在大串中第一次出现的索引2.使用substring(int beginIndex)方法,获得减去小串之前的所有字符串后的新字符串(小串出现的第一次索引+小串的长度)*/public class StringTest {public static void main(String[] args) {String s1 = "nojavaqwejavaqwewqjavaoiu";String s2 = "java";int count = 0;//定义变量统计s2在s1中出现的次数int index;//定义变量获得S2出现时的索引//确定s2的索引存在while((index=s1.indexOf(s2))!=-1) {count++;s1= s1.substring(index + s2.length());//获得每次s2出现后的字符串变化System.out.println(s1);}System.out.println("java在字符串中出现了: "+count+" 次");}}





原创粉丝点击