zoukankan      html  css  js  c++  java
  • 大串和小串

    首先键盘录入2个字符串
            A:定义一个统计变量=0;
            B:在大串中查找小串是否存在,用 int indexOf(String str):返回指定字符在此字符串中第一次出现处的索引。
                a:如果返回的索引值是-1,则说明 大串中并不存在这个小串,输出统计变量
                b:返回的若不是-1,则是这个小串的第一个字符在大串中的索引,这个时候统计变量++
            C:从得到的索引开始,再加上小串的长度,到字符串的最后,开始截取一个新的字符串,再把这个字符串赋值给大串,替换之前的大串
              String substring(int start):从指定位置开始截取字符串,默认到末尾。
            D:再次从B开始循环,直到得到的新字符串没有了这个小串,也就是B中的a
        以上分析定义为一个方法,方法的两个要素:
            a:返回值:int
            b:参数列表:两个字符串,大串和小串

    package stringTest;
    
    import java.util.Scanner;
    
    public class StringSubstringTest {
        public static int getCount(String max,String min){
            int count=0;
            int index;
            while ((index=max.indexOf(min))!=-1) {
              count++;
              max=max.substring(max.indexOf(min)+min.length());
            }
            return count ;
    
        }
        public static void main(String[] args) {
            Scanner scanner=new Scanner(System.in);
            System.out.println("输入大串");
            String maxString=scanner.nextLine();
            System.out.println("输入小串");
            String minString=scanner.nextLine();
             int count = getCount(maxString,minString);
             System.out.println(minString+"在"+maxString+"中出现了"+count+"次");
        }
    
    }

    indexof()返回的是起始的下标

    substring(beginindex,endindex),截前不截后

  • 相关阅读:
    危机下,你还敢提加薪吗?
    大白兔奶糖三聚氰胺事件后21日起重新上架
    15个nosql数据库
    向网页设计师推荐15个很棒的网站
    腾讯新浪通过IP地址获取当前地理位置(省份)的接口
    5个最顶级jQuery图表类库插件Charting plugin
    12种JavaScript MVC框架之比较
    企业网站设计的启示
    游戏引擎大全
    推荐几份能够帮助你学习 CSS3 的实用帮助手册
  • 原文地址:https://www.cnblogs.com/Darius-Bennett/p/7859619.html
Copyright © 2011-2022 走看看