java中字符串的常见几个操作

//去除字符串前后空格

public class Trim {

  public static void main(String[] args) {
  String s=" t e s t ";
  System.out.println(s);
  s=s.trim();//去掉前后空格
  System.out.println(s);
  s=s.replace(" ", ""); //去掉所有空格
 //s=s.replace("+", "");s=s.replace("\\s*", "");
 System.out.println(s);

 }
}

//对字符串指定位置进行反转
public class Reverse {
public static void main(String[] args) {
    String str="abcfdeg";
  // StringBuffer b=new StringBuffer(str);
  // str=b.reverse().toString();
  // System.out.println(b); //全部进行反转
   System.out.println(str);
   str=reverse(str,2,5); //adfcbeg
   System.out.println(str);
}
  public static String reverse(String s,int start,int end){
    char[] ch=s.toCharArray();
    char temp;
    while(start<end){
      temp=ch[start-1];
      ch[start-1]=ch[end-1];
      ch[end-1]=temp;
      start++;
      end--;
 }
    s=String.copyValueOf(ch);
    return s;
 }

}

//获取一个字符串在另一个字符串中出现的次数
public class Count {
public static void main(String[] args) {
    String str1="abc";
    String str2="dfaabcfdfabcfdskabcadfabfdbc";
    int sum=getSubCount(str2,str1);
    System.out.println(sum);

}
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 class SubMax {
public static void main(String[] args) {
    String str1="adafhellodfjlafj";
    String str2="dffddsahelloferhhhfsde";
    String temp=getSubmax(str1,str2);
    System.out.println(temp);
}

public static String getSubmax(String str1, String str2) {
   String max=(str1.length()>str2.length())?str1:str2;
   String min=max==str1?str2:str1;
   for(int i=0;i<min.length();i++){
    for(int j=0, k=min.length()-i;k!=min.length()+1;j++,k++){
     String str=min.substring(j, k);
     if(max.contains(str)){
       return str;
     }
   }
 }
  return "";
 }
}

 

posted on 2016-11-27 09:57  pfq  阅读(111)  评论(0)    收藏  举报

导航