删除字符数组中重复的元素

预备知识:

0表示整数,'0'表示0字符,'\0'表示ASCII码值为0的字符

如果是 “字符串数组” 转 “字符串”,只能通过循环,没有其它方法 
[java] view plain copy
  1. String[] str = {"abc""bcd""def"};  
  2. StringBuffer sb = new StringBuffer();  
  3. for(int i = 0; i < str.length; i++){  
  4.   sb. append(str[i]);  
  5. }  
  6. String s = sb.toString();  
如果是 “字符数组” 转 “字符串” 可以通过下边的方法 
 
 
[java] view plain copy
  1. String st=new String(c,0, l);  //第一个位置为字符数组名字,第二个为开始的位置,第三个为字符数组的长度  
  2. return st;  
1. 蛮力法。(最简单的方法是把 字符串看成一个 字符数组,对该字符数组使用双重循环遍历,如果发现有重复的字符,就把该字符置为'\0',最后再把这个字符数组中所有的'\0'去掉,此时得到的字符串就是删除重复字符后的目标字符串
 
 
[java] view plain copy
  1. public class Test {  
  2.     public static void main(String args[]){      
  3.            String str="abcaabcd";     
  4.            str=removeDuplicate(str);       
  5.            System.out.print(str);        
  6.     }  
  7.         private static String removeDuplicate(String str) {  
  8.         char[] c=str.toCharArray();   //把字符串str转化为字符数组c[]  
  9.         int len=c.length;  
  10.         for(int i=0;i<len;i++){  
  11.             if(c[i]=='\0')  
  12.                 continue;  
  13.             for(int j=i+1;j<len;j++){  
  14.                 if(c[j]=='\0')  
  15.                     continue;  
  16.                 if(c[i]==c[j])  
  17.                     c[j]='\0';  
  18.             }  
  19.         }  
  20.         int l=0;  
  21.         for(int i=0;i<len;i++){      //得到每个元素只有一个的字符数组c[]  
  22.             if(c[i]!='\0')   
  23.                 c[l++]=c[i];  
  24.         }   
  25.           
  26.         System.out.println("l表示的是字符串的个数:"+l);  
  27.         //将字符数组转化为字符串两种方法  
  28.         /* 
  29.           String st=new String(c,0, l);  //第一个位置为字符数组名字,第二个为开始的位置,第三个为字符数组的长度 
  30.               return new String(st); 
  31.             */  
  32.         return new String(c,0,l);  //第一个位置为字符数组名字,第二个为开始的位置,第三个为字符数组的长度  
  33.     }  

猜你喜欢

转载自blog.csdn.net/qq_41086461/article/details/78566855
今日推荐