zoukankan      html  css  js  c++  java
  • 判断i在字符串中出现的次数(2016.1.12P141-1)

     1 // 方法一,利用substring截取获得出现的次数
     2 
     3         String number = "iminigrikejijavabi";
     4 
     5         String a = number;
     6 
     7         int cs = 0;// 次数
     8 
     9         for (int i = 0; i < number.length() - 1; i++) { // 循环截取
    10 
    11             if (a.indexOf("i") >= 0) { // 判断子字符串是否还有i
    12 
    13                 cs++;
    14             }
    15             a = a.substring(a.indexOf("i") + 1); // 将截取的子字符串重新赋值,即将字符串变短
    16         }
    17         System.out.println("(方法一)字符i出现的次数:" + cs);
    18 
    19         // 方法二,利用replace替换来获得出现的次数
    20 
    21         int i = number.length();// 替换以前的字符串长度
    22 
    23         int j = number.replace("i", "").length();
    24 
    25         System.out.println("(方法二)字符i出现的次数:" + (i - j));
    26 
    27         // 利用split分割的方法
    28 
    29         String[] in = number.split("i");
    30         if (number.endsWith("i")) {
    31 
    32             System.out.println("(方法三)字符i出现的次数:" + (in.length));
    33         } 
    34         else {
    35 
    36             System.out.println("(方法三)字符i出现的次数:" + (in.length - 1));
    37         }
    38 
    39         // 利用split分割的方法
    40         int cs1 = 0;
    41 
    42         String[] in1 = number.split("");
    43 
    44         for (String y : in1) {
    45             if (y.equals("i")) {
    46                 cs1++;
    47             }
    48         }
    49         System.out.println("(方法四)字符i出现的次数:" + cs1);

    运行的结果:

  • 相关阅读:
    WPF DelegateCommand 出现Specified cast is not valid
    WPF DelegateCommand 出现Specified cast is not valid
    WPF DelegateCommand 出现Specified cast is not valid
    win10 sdk 是否向下兼容
    win10 sdk 是否向下兼容
    win10 sdk 是否向下兼容
    PHP extract() 函数
    PHP end() 函数
    PHP each() 函数
    PHP current() 函数
  • 原文地址:https://www.cnblogs.com/zhengfengyun/p/5125233.html
Copyright © 2011-2022 走看看