A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© zhangfurui 中级黑马   /  2015-8-13 19:54  /  4257 人查看  /  15 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

10黑马币
如何判断指定字符串在另外字符串中,总共出现的次数,每次出现对应的索引是多少?

最佳答案

查看完整内容

此题迭代最方便,加上String的两个基本方法,代码如下: 辛苦赚技能分,看在这么认真的样子,赏点吧。

15 个回复

倒序浏览
此题迭代最方便,加上String的两个基本方法,代码如下:
辛苦赚技能分,看在这么认真的样子,赏点吧。
  1. /**
  2. * 题目:如何判断指定字符串在另外字符串中,总共出现的次数,每次出现对应的索引是多少?
  3. * 思路:(迭代法)
  4. * 1、用String a调用indexOf(String b)可获取b在a中第一次出现的位置x,并打印
  5. * 2、用String a调用substring(int x+b.length())获取b前一次出现的位置之后的字符串,并将此字符串赋给a重复同样的步骤
  6. * 3、直到indexOf方法返回-1;
  7. * @author 王艳静
  8. *
  9. */
  10. public class Test1 {
  11.         static String str = "aslovedfghlovejertloveloveyuilovexcvblovefghjlove";
  12.         static String s = "love";
  13.         static int index =0,i=1,pos = 0;
  14.        
  15.         public static void main(String[] args) {
  16.                
  17.                 fg(str);

  18.         }
  19.        
  20.         static void fg(String ss){
  21.                
  22.                 if((pos = ss.indexOf(s))!=-1){
  23.                        
  24.                         index += pos;
  25.                         System.out.println(s+"第"+(i++)+"次出现的位置:"+index);
  26.                         index += s.length();
  27.                         fg(ss.substring(pos+s.length()));
  28.                
  29.                 }
  30.         }

  31. }
复制代码
回复 使用道具 举报
本帖最后由 Coolman 于 2015-8-13 21:28 编辑

这里只是提供一个思路,至于累加出现的次数和记录每次出现的索引需要楼主自己实现
  1. /**
  2.         如何判断指定字符串在另外字符串中,总共出现的次数,每次出现对应的索引是多少?
  3. */

  4. /*
  5.         使用 indexOf 实现检索
  6.                 indexOf 方法用于实现在字符串中检索另外一个字符串
  7.                 String 提供几个重载的 indexOf 方法
  8.         int indexOf(String str)
  9.                 在字符串中检索 str ,返回其第一次出现的位置,如果找不到则返回 -1
  10.         int indexOf(String str, int fromIndex)
  11.                 从字符串的 fromIndex 位置开始检索
  12. */

  13. /*
  14.         思路:
  15.                 先使用 int indexOf(String str) 返回第一次出现的位置
  16.                 String str = ""; // 目标串
  17.                 String substr = ""; // 字串,要检索的指定字符串
  18.                 int index = str.indexOf(substr); // 第一次出现的位置,索引从 0 开始
  19.                 再从第一次出现的位置 +1 开始往后检索,直到字符串可以出现的最后一个位置
  20.                 int fromIndex = index + 1;
  21.                 for (fromIndex; fromIndex < (str.length() - substr.length()); fromIndex ++) {
  22.                         index = str.indexOf(substr, fromIndex);
  23.                 }
  24. */
复制代码



点评

赞一个!  发表于 2015-8-13 21:34
回复 使用道具 举报
好吧,这块儿只是我还没有学到。顶一下吧!
回复 使用道具 举报
本帖最后由 肖天长 于 2015-8-13 22:26 编辑

class Demo
{
         public static int getSubCount(String str,String key)
        {
                int count=0;//定义计数器记录次数
                int index=0;//定义索引,因为字符串每次出现的位置不同
                while((index=str.indexOf(key,index))!=-1)
                {
                        index=index+key.length();//每次出现的索引+要找的字符串的长度
                        count++;
                }
                return count;
        }
        public static void main(String[] args)
        {
                String str ="shhasuhhiaiehnehhh";
                System.out.println(getSubCount(str,"hh"));
        }
}
回复 使用道具 举报
string str = "sfsfluljslfnslafuensdfre";
string s="s";

int count= str.Length - str.Replace(s,"").Length;
回复 使用道具 举报
public static void main(String[] args) {  
        String s = charCount("afasdgghgdfgsdfasf*asd*fasdf-ioue/asdfsdfgjsd*asf/");  
        System.out.println(s);  
    }  
  
    private static String charCount(String s) {  
        char[] ch =  s.toCharArray();//字符串转成字符数组  
        //因为字母和次数之间存在键值对关系,而且字母还要有序(TreeMap默认升序),所以使用TreeMap集合  
        TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();  
        int count = 0;//定义变量存放次数  
        for(int i=0;i<ch.length;i++)//该for循环实现判断以及将每个字母以及出现的次数存放到tm中  
        {   //判断是不是字母  
            if(!('a'< ch[i] && ch[i]<'z' || 'A'< ch[i] && ch[i]<'Z'))  
                continue;  
            Integer value = tm.get(ch[i]);//取出当前字母在tm中的值  
            if(value != null)//如果值存在,说明该字母已经出现过,将值取出自增再存放  
                count = value;  
            count++;  
            tm.put(ch[i], count);  
            count = 0;//对次数清零一次以便重新在接收取出的值  
        }  
        //定义一个容器存放键和值  
        StringBuilder sb = new StringBuilder();  
        //取出tm中的键Set<E>射关系存放到Set集合以便迭代。  
        Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();  
        Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();  
        while(it.hasNext())  
        {  
            Map.Entry<Character, Integer> me = it.next();  
            Character chs = me.getKey();  
            Integer value = me.getValue();  
            sb.append(chs+"("+value+")  ");  
        }  
        return sb.toString();  
    }  
  
回复 使用道具 举报
学习学习
回复 使用道具 举报
backin 中级黑马 2015-8-14 21:39:59
9#
本帖最后由 backin 于 2015-8-14 21:43 编辑

用indexof的indexof(str,startindex)可完成最小迭代。
  1.    
  2. public static void main(String [] args)
  3.     {
  4.         String str = "asdfasdgsdasdfasdgsdasdhewefAsdAA";// 目标串
  5.         String s = "sd";// 子串
  6. //      ArrayList index = new ArrayList();// 用于存放检索到的子串的index
  7.         int fromIndex = 0;// 当前索引
  8.         int count = 0;// 统计出现的次数
  9.         
  10.         while (true)
  11.         {
  12.             fromIndex = str.indexOf(s , fromIndex);// 不解释
  13.             if (fromIndex == -1 || fromIndex == str.length() - 1)// 指定退出条件
  14.             {
  15.                 break;
  16.             }
  17.             count++;
  18. //          index.add(fromIndex++);
  19.             
  20.             System.out.print(s + "出现第 <" + count + ">次,出现的位置为:" + (fromIndex++)
  21.                     + "\n");
  22.         }
  23. //        System.out.print(s + "出现第 <" + count + ">次,出现的位置为:");
  24. //        for (int i = 0; i < index.size(); i++)
  25. //        {
  26. //            System.out.print(index.get(i)+"  ");
  27. //        }
  28.       
  29.     }
  30.    
复制代码






回复 使用道具 举报
public class Index2 {
        public static void main(String[] args) {
                String s1 = "123llleiajae123opes123";
                String s2 = "123";
                char[] arr1 = s1.toCharArray();
                char[] arr2 = s2.toCharArray();
                if (arr1.length < arr2.length) {
                        System.out.println(s1 + "中没有" + s2 + "这个字符串");

                }
                int num = -1;
                int count = 0;
                for (int x = 0; x < arr1.length; x++) {
                        if ((arr1[x] == arr2[0]) && (arr1[x + 1] == arr2[1])
                                        && (arr1[x + 2] == arr2[2])) {
                                count++;
                                num = x;
                                System.out.println(s2 + "第" + count + "次在" + s1 + "出现的索引是:"
                                                + num);

                        }
                }
                if (num == -1) {
                        System.out.println(s1 + "中没有" + s2 + "这个字符串");

                } else {
                        System.out.println(s1 + "中总共出现了" + count + "次" + s2 + "这个字符串");

                }

        }

}
回复 使用道具 举报
下边是我给你做的例子,有注释,.
public class StringTest3 {

        public static void main(String[] args) {
               
                // 定义大字符串
                String bigStr = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun" ;
               
                // 定义小字符串
                String minStr = "java";
               
                // 调用方法
                int count = getCount2(bigStr , minStr);
               
                // 输出
                System.out.println("出现的次数是: " + count + "次");
        }
       
        /**
         * 代码优化
         * @param bigStr
         * @param minStr
         * @return
         */
        public static int getCount2(String bigStr , String minStr){
               
                // 定义一个统计变量
                int count = 0 ;
               
                // 定义一个索引
                int index ;
               
                while((index = bigStr.indexOf(minStr)) != -1){
                       
                        // 对统计变量做自增1的动作
                        count++ ;
                       
                        // 截取字符窜
                        bigStr = bigStr.substring(index + minStr.length()) ;
                }
               
                return count ;
               
        }
       
       
        /**
         * 查找大串中小串出现的次数
         * @param bigStr
         * @param minStr
         * @return
         */
        public static int getCount(String bigStr , String minStr){
               
                // 定义一个统计变量
                int count = 0 ;
               
                // 查找
                int index = bigStr.indexOf(minStr) ;
               
                // 判断
                while(index != -1){
                       
                        // 对统计变量做自增1的动作
                        count++ ;
                       
                        // 截取字符窜
                        bigStr = bigStr.substring(index + minStr.length()) ;
                       
                        // 查找
                        index = bigStr.indexOf(minStr) ;
                       
                }
               
                return count ;
               
        }
}
回复 使用道具 举报
哈哈 新手我是来学习的
回复 使用道具 举报
     public static void main(String [] args)     {         String str = "asdfasdgsdasdfasdgsdasdhewefAsdAA";// 目标串         String s = "sd";// 子串 //      ArrayList index = new ArrayList();// 用于存放检索到的子串的index         int fromIndex = 0;// 当前索引         int count = 0;// 统计出现的次数                  while (true)         {             fromIndex = str.indexOf(s , fromIndex);// 不解释             if (fromIndex == -1 || fromIndex == str.length() - 1)// 指定退出条件             {                 break;             }             count++; //          index.add(fromIndex++);                          System.out.print(s + "出现第 <" + count + ">次,出现的位置为:" + (fromIndex++)                     + "\n");         } //        System.out.print(s + "出现第 <" + count + ">次,出现的位置为:"); //        for (int i = 0; i < index.size(); i++) //        { //            System.out.print(index.get(i)+"  "); //        }             }     
回复 使用道具 举报
遍历,for循环中i++代表出现次数,每次出现,输出索引
回复 使用道具 举报
还没学到呢。涨知识了。谢谢楼主
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马