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),截前不截后

  • 相关阅读:
    使用S7netplus存取西门子PLC字符串数据
    学习使用Nginx配置服务器
    Bootstrap4设置footer固定在底部
    ASP.NET Core MVC项目Razor页面实时编译
    在Asp.NET Core MVC项目中通过Libman安装Bootstrap
    在Asp.Net Core Web项目中使用不同的环境
    C#简单使用System.Threading.Timer
    在ASP.Net Core Web API中使用Swagger进行版本控制
    ASP.Net Core Web API解决跨域问题
    LeetCode刷题-- 搜索插入位置
  • 原文地址:https://www.cnblogs.com/Darius-Bennett/p/7859619.html
Copyright © 2011-2022 走看看