本帖最后由 奋发吧小白 于 2014-11-5 10:22 编辑
- package String类小练习;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import java.util.TreeMap;
- public class MyTrim {
- public static void main(String[] args) {
- String s1 = " akkcdehellowaskkjdl ";
- String s2 = "cshellowds";
- System.out.println(myTrim(s1));
- System.out.println(myReverse(s1));
- System.out.println(getSubCount(s1,"kk"));
- System.out.println(getMaxSubStr(s1,s2));
- getCharCoutInStr(s1);
- }
- //去除字符串两端的空格
- public static String myTrim(String s)
- {
- int start = 0;
- int end = s.length()-1;
- while(start < end && s.charAt(start)==' ')
- start++;
- while(start < end &&s.charAt(end)==' ')
- end--;
- String newStr = s.substring(start,end+1);
- return newStr;
- }
- //翻转字符串
- public static String myReverse(String s)
- {
- String newStr = new String();
- char [] chs = s.toCharArray();
- for(int i=chs.length-1;i>=0;i--)
- {
- newStr+=chs[i];
- }
- return newStr;
- }
- //获取一个字符串在另一字符串中出现的次数
- public static int getSubCount(String s,String key)
- {
- int count = 0;//计数器,记录每次出现的次数
- int index = 0;//记录每次出现的角标位置
- while((index =s.indexOf(key))!=-1)
- {
- count++;
- s = s.substring(index+key.length(),s.length());
- }
- return count;
- }
- //获取两个字符串中相同的最大子串
- public static String getMaxSubStr(String s1,String s2)
- {
- String maxStr = new String();
- String max = (s1.length()>s2.length())?s1:s2;
- String min = (max == s1)?s2:s1;
- for(int i=0;i<min.length();i++)
- {
- for(int start = 0,end = min.length()-1;end!=min.length()+1;start++,end--)
- {
- maxStr = min.substring(start,end);
- if(max.contains(maxStr))
- {
- return maxStr;
- }
- }
- }
- return null;
- }
- //获取字符在字符串出现的次数
- public static void getCharCoutInStr(String s)
- {
- int count = 0;
- Map<Character, Integer> mp = new TreeMap<Character, Integer>();
- char [] chs = s.toCharArray();
- for(int i = 0;i<chs.length;i++)
- {
- if(chs[i]>='a'&&chs[i]<='z'||chs[i]>='A'&&chs[i]<='Z')
- {
- if(!mp.containsValue(chs[i]))
- {
- mp.put(chs[i], 1);
- }
- else
- {
- count = mp.get(chs[i])+1;
- mp.put(chs[i], count);
- }
- }
-
- }
- //取出集合中的元素
- Set<Character> keySet = mp.keySet();
- Iterator<Character> it = keySet.iterator();
- while(it.hasNext())
- {
- Character key = it.next();
- Integer value = mp.get(key);
- System.out.print(key+"("+value+")");
- }
- }
- }
复制代码
String类的常见的四个小练习:
1:自己定义一个方法去除一个字符串两端的空格(不能使用trim()方法)
2:自定义一个方法翻转字符串
3:获取一个字符串在另一个字符串中出现次数
4:获取两个字符串中相同的最大子串
“abcdehellowaskjdl” “cshellowds” 最大子串为“hellow” - <blockquote><font size="2">//获取字符在字符串出现的次数</font>
复制代码
|