如何存储字符串的不同字符

时间:2019-03-03 06:15:32

标签: java string

public class NoDuplicate { 
    static final int NO_OF_CHARS = 256; 

    /* Print duplicates present in the passed string */
    static void printDistinct(String str) 
    { 
        // Create an array of size 256 and count of 
        // every character in it 
        int[] count = new int[NO_OF_CHARS]; 

        /* Count array with frequency of characters */
        int i; 
        for (i = 0; i < str.length(); i++) 
            if(str.charAt(i)!=' ') 
                count[(int)str.charAt(i)]++; 
        int n = i; 

        // Print characters having count more than 0 
        for (i = 0; i < n; i++) 
            if (count[(int)str.charAt(i)] == 1) 
                System.out.print(str.charAt(i)); 
    } 

    /* Driver program*/
    public static void main(String args[]) 
    { 
        String str = "SHINCHAN"; 
        printDistinct(str); 
    } 
} 

我正在尝试将不同的字符存储在字符串中。问题是我的代码删除了所有重复的元素。示例:

  

输入:SHINCHAN

     

实际输出:SICA

     

所需的输出:SHINCA(我想将每个元素存储一次)

3 个答案:

答案 0 :(得分:4)

您可以使用LinkedHashSet来实现相同的功能:

static void printDistinct(String str) {
    Set<Character> origSet = new LinkedHashSet<Character>();
    StringBuilder concat = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        if (origSet.add(str.charAt(i))) {
            concat.append(str.charAt(i));
        }
    }
    System.out.println(concat);
}

如果您使用的是Java-8,则可以执行以下操作:

str.chars().mapToObj(e -> Character.toString((char) e))
           .distinct()
           .forEach(System.out::println);

答案 1 :(得分:3)

static void printDistinct(String str) {
        String s="";
        Set<Character> origSet = new LinkedHashSet<Character>();
        for (int i = 0; i < str.length(); i++) {
            origSet.add(str.charAt(i));
        }
        System.out.println(origSet);
        for(char c:origSet) {
            s=s+c;
        }
        System.out.println(s);
    }

此代码将存储您的字符串

答案 2 :(得分:0)

您最好的选择是在第一个循环中打印字符。第一次看到它们时将它们打印出来。然后,您可以完全摆脱第二个循环。

/* Count array with frequency of characters */
int i; 
for (i = 0; i < str.length(); i++) {
    if (str.charAt(i)!=' ') {
        count[(int)str.charAt(i)]++; 
        if (count[(int)str.charAt(i)] == 1) {
            System.out.print(str.charAt(i));
        }
    }
}

顺便说一下,将str.charAt(i)保存在变量中会使代码更易于阅读。

/* Count array with frequency of characters */
int i; 
for (i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (ch != ' ') {
        count[(int) ch]++; 
        if (count[(int) ch] == 1) {
            System.out.print(ch);
        }
    }
}
相关问题