String方法取字符出现次数和字符最大相同

简介:
[java]  view plain  copy
 print ?
  1. class  Test  
  2. {  
  3.     public static void main(String[] args)   
  4.     {  
  5.         String str  = "dasdalldsdslldsdszxll";  
  6.         System.out.println("count="+get(str,"ll"));//打印ll出现的次数  
  7.         String s1 = "asdhellovdvdvv";  
  8.         String s2 = "cvfhelloff";  
  9.         System.out.println("temp="+gett(s1,s2));//打印两个字符串最大相同的部分  
  10.     }  
  11. /*  public static int get(String str,String key) 
  12.     { 
  13.         int count = 0; 
  14.         int index = 0;//定义一个位置 
  15.  
  16.         while((index = str.indexOf(key))!=-1)//直到取不到需要的字符结束循环 
  17.         { 
  18.             str = str.substring(index + key.length());//字符串长度变化获得新的字符串 
  19.             count++; 
  20.         } 
  21.         return count; 
  22.     } 
  23.     */  
  24. //第二种方法,大同小异  
  25.  public static int get(String str,String key)  
  26.     {  
  27.         int count = 0;  
  28.         int index = 0;  
  29.   
  30.         while((index = str.indexOf(key,index))!=-1)  
  31.         {  
  32.             index = index + key.length();  
  33.             count ++;  
  34.         }  
  35.         return count;  
  36.     }  
  37.     public static String gett(String s1,String s2)  
  38.     {  
  39.         String max = "";  
  40.         String min = "";  
  41.         max = s1.length() > s2.length()?s1:s2;  
  42.         min = max == s1?s2:s1;//取短的字符串比较节省内存  
  43.         for(int x = 0;x < min.length();x++)  
  44.         {  
  45.             for(int y = 0,z = min.length() -x;z!=min.length()+1;y++,z++)  
  46.             {  
  47.                 String temp = min.substring(y,z);  
  48.                 if(max.contains(temp))  
  49.                     return temp;  
  50.             }  
  51.         }  
  52.         return "";  
  53.     }  
  54. }  



转载:http://blog.csdn.net/chaoyu168/article/details/49280517

目录
相关文章
|
2月前
|
Java
Java String split()方法详细教程
Java String split()方法详细教程
27 0
|
2月前
|
存储 C++ 索引
C++ string容器-字符存取讲解
C++ string容器-字符存取讲解
26 0
|
2月前
|
Java 索引
Java中String方法学习总结_kaic
Java中String方法学习总结_kaic
|
2天前
int 和 String 互相转换的多种方法
int 和 String 互相转换的多种方法
|
16天前
|
存储 缓存 Java
|
18天前
|
C++
【C++】std::string 转换成非const类型 char* 的三种方法记录
【C++】std::string 转换成非const类型 char* 的三种方法记录
7 0
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
2月前
|
Java 索引
【Java】String类常用方法总结
【Java】String类常用方法总结
20 0
|
2月前
|
存储 算法 C++
string容器一字符事查找和替换
string容器一字符事查找和替换
12 0
|
2月前
|
机器学习/深度学习 Java 索引
39、一篇文章弄懂 Java 正则表达式中的量词、贪婪、勉强、独占和 String 的 matches 方法的底层【个人感觉非常值得学习】
39、一篇文章弄懂 Java 正则表达式中的量词、贪婪、勉强、独占和 String 的 matches 方法的底层【个人感觉非常值得学习】
32 0