1.定义一个将两边空格去掉的方法
2.将一个字符串进行反转
将一个字符串指定位置反转
3.获取一个字符串在另一个字符串中出现的次数。
asfkkaswkkzxcwkkqwqswkkcxzkk kk出现的次数
4.获取两个字符串中最大相同的子串。
asqehelloasdxzc
zqhellodc
- class Test
- {
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- public static void main(String[] args)
- {
- //String a = new String(" ab cd ");
- //sop(method(a));
- //sop(method_2(a));
- //String a = "asfkkaswkkzxcwkkqwqswkkcxzkk";
- //sop(method_3(a,"kk"));
- String s1 = "asqehelloasdxzc";
- String s2 = "zqhellodc";
- sop(method_4(s1,s2));
- }
-
- //获取两个字符串中最大相同的子串。
- public static String method_4(String s1 ,String s2)
- {
- String max , min;
- max = (s1.length() > s2.length())?s1:s2;
- min = (max == s1)?s2:s1;
- for (int x = 0; x < min.length() ; x++)
- {
- for (int y = 0 , z = min.length()-x; z < min.length()+1 ;y++,z++ )
- {
- String temp = min.substring(y,z);
- if(max.contains(temp))
- return temp;
- }
- }
- return "-1";
- }
- //获取一个字符串在另一个字符串中出现的次数。
- public static int method_3(String str ,String key)
- {
- int count = 0,index = 0;
- while((index = str.indexOf(key)) != -1)
- {
- str = str.substring(index+key.length());
- count++;
- }
-
- return count;
-
- }
- //将一个字符串指定位置反转
- public static String method_2(String str ,int x ,int y)
- {
- //将其转换成字符数组
- char[] ch = str.toCharArray();
- //将其反转
- fan(ch,x,y);
- //return将反转的数组转换成字符串
- return String.valueOf(ch);
- }
- //将一个字符串进行反转
- public static String method_2(String str)
- {
- return method_2(str,0,str.length()-1);
- }
- private static void fan(char[] ch,int x ,int y)
- {
- for (int a = x , b = y ; a<b ;a++,b-- )
- {
- temp(ch,a,b);
- }
- }
- private static void temp(char[]ch,int x,int y )
- {
- char temp = ch[x];
- ch[x] = ch[y];
- ch[y] = temp;
- }
- //将两边空格去掉的方法
- public static String method_1(String str)
- {
- //将其转换成字符数组
- char[] ch = str.toCharArray();
- int start = 0 , end = str.length()-1;
- //判断空格,记录不是空格的首尾角标
- while(start <= end && str.charAt(start) == ' ')
- start++;
- while(start <= end && str.charAt(end) == ' ')
- end--;
- return str.substring(start , end+1) ;
- }
- }
复制代码
|
|