日期:2014-05-20  浏览次数:20635 次

字符串,求教
.解析一个字符串,对字符串中重复出现的字符,只在第一次出现时保留
 如: abdabbefgf 结果为 abdefg

------解决方案--------------------
Java code
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class Test2 {

    public static void main(String[] args){
        
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        List<Character> list = new ArrayList<Character>();
        for(int i=0; i<str.length(); i++){
            if(!list.contains(str.charAt(i))){
                list.add(str.charAt(i));
            }
        }
        System.out.println(list);
    }
}

------解决方案--------------------
Java code

import java.util.LinkedHashSet;
public class Test{
    public static void main(String args[]){
        LinkedHashSet<Character> set = new LinkedHashSet<Character>();
        String s = "abdabbefgf";
        for(Character c:s.toCharArray()){
            if(set.add(c)){
            System.out.print(c);    
            }
        }
        System.out.println(set);
    }
}

------解决方案--------------------
for example
Java code
String s = "abdabbefgf";
StringBuilder buf = new StringBuilder();
char[] c = s.toCharArray();
for (int i=0; i<c.length; i++) {
    if (s.indexOf(c[i]) == i) buf.append(c[i]);
}
System.out.println(buf);