zoukankan      html  css  js  c++  java
  • 用JAVA写查询一个字符串中是否包含另外一个字符串以及出现的次数

    package JAVA;

    import java.awt.List;
    import java.util.ArrayList;
    /**
     *
     * @author 梁小鱼
     *
     */
    public class MyTest {

     public static void main(String[] args) {
      //查找字符串在目标字符串是否存在
      Boolean isExit = IsExit("f","abfsdfsdkjl;fas;dlfsldf;asdfsdfaszdf");
      System.out.println(isExit);
     }
     
     private static Boolean IsExit(String strson, String strmother ) {
      //设置是否存在标志位
      Boolean Isflag = false;
      // 获得母串的长度
      Integer strmotherLength = strmother.length();
      // 获得子串的长度
      Integer strsonLength = strson.length();
      
      if (strmother==null||strmotherLength<strsonLength||strson.equals("")||strson==null) {
       return false;
      }
      System.out.println("输入的母串为:" + strmother);
      System.out.println("输入的子串为:" + strson);
      //存放结果的数组
      ArrayList<Boolean> reasonArr = new ArrayList<Boolean>();
      //字符出现次数
      Integer appTime = 0;
      //将母串转为字符数组
      char[] charArrayMother = strmother.toCharArray();
      //以子串长度为单位遍历母串数组
      for (int i = 0; i < (charArrayMother.length - strsonLength +1); i++) {
       //遍历起点为0,终点为数组长度减去子串长度
       //以子串长度  为最小单位 遍历比较
       //写一个比较的字方法,传入的参数有母串数组,当前遍历位置,子串
       Integer flag = compare(charArrayMother,strson,i);
       if (flag == 1) {
        reasonArr.add(true);
       }else {
        reasonArr.add(false);
       }
      }
      
      //在此结算
      for (Boolean bool : reasonArr) {
       if (bool==true) {
        appTime += 1;
        
       }
      }
      System.out.println("字符:" + strson + "  在   " + strmother + "   中出现的次数为:" + appTime + "次!");
      if (appTime>0) {
       return true;
      }
      return Isflag;
     }
     /**
      * 处理比较的方法
      * @param charArrayMother
      * @param strson
      * @param i
      * @return
      */
     private static Integer compare(char[] charArrayMother, String strson, int i) {
      // 取出当前遍历位置,所形成的子串长度单位的字符
      // 创建一个字符床存放拿出来的字符
      String comstr = "";
      for (int j = 0; j < strson.length(); j++) {
       char c = charArrayMother[i+j];
       comstr += String.valueOf(c);
      }
      System.out.println("第"+ (i+1) + "截取的字符串为:" + comstr);
      if (strson.equals(comstr)) {
       return 1;
      }
      return 0;
     }
    }

  • 相关阅读:
    双向循环链表
    字符串拷贝
    div样式调整.txt
    解析xml的单个节点值和循环节点消息体
    C++中的string
    正则表达式教程
    一个很好的Qt教程个人主页
    单射、双射与满射
    ISO C++ forbids declaration of * with no type
    一个中学生的个人主页
  • 原文地址:https://www.cnblogs.com/liangxiaoyu/p/6227700.html
Copyright © 2011-2022 走看看