Java 如何计算字符串中唯一字符的数量?- 更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22646218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:04:00  来源:igfitidea点击:

How do I count the number of unique characters in a string? - Updated

javacountcharacterunique

提问by newJavaUser

For example, the string "abc" should give 3 unique characters, while the string "abcccd" would give 4 unique characters. I'm not allowed to use Map, HashMap, TreeMap, Set, HashSet, StringBuffer or TreeSet in this.

例如,字符串“abc”应给出 3 个唯一字符,而字符串“abcccd”应给出 4 个唯一字符。我不允许在这里使用 Map、HashMap、TreeMap、Set、HashSet、StringBuffer 或 TreeSet。

So far I'm trying to use a for loop but when I run the program I keep getting 0 unique characters. I'm kind of new at Java so I really have no idea what I'm doing.

到目前为止,我正在尝试使用 for 循环,但是当我运行该程序时,我不断收到 0 个唯一字符。我是 Java 新手,所以我真的不知道我在做什么。

Edit: so I changed the code around and I'm getting a result but it ends up being 1 less than what I want. I'll type in 'abc' and the result will come up as "2 unique characters" instead of three. To counter that I put (uniqueChars + 1) in the println statement. Is this a good correction? If the user puts nothing, it will still say that there's 1 unique character.

编辑:所以我改变了代码,我得到了一个结果,但结果比我想要的少 1。我将输入“abc”,结果将显示为“2 个唯一字符”而不是三个。为了反驳我将 (uniqueChars + 1) 放在 println 语句中。这是一个很好的修正吗?如果用户什么都不放,它仍然会说有 1 个独特的字符。

Updated code:

更新代码:

    userText = userText.toLowerCase(); // userText is declared earlier in the program 
                                       // as the user's input. Setting this to lowercase 
                                       // so it doesn't say "a" and "A" are two different 
                                       // characters.
    int uniqueChars = 0;
    for (int i = 0; i < lengthText-1; i++) { // lengthText is declared earlier 
                                              // as userText.length();
        if (userText.charAt(i) != userText.charAt(i+1))
            uniqueChars++;
    }
    System.out.println("there are " + (uniqueChars + 1) + " unique characters in your string.");
}

采纳答案by Veluria

This is what I came up with:

这就是我想出的:

public static int countUniqueCharacters(String s) {
    String lowerCase = s.toLowerCase();
    char characters[] = lowerCase.toCharArray();
    int countOfUniqueChars = s.length();
    for (int i = 0; i < characters.length; i++) {
        if (i != lowerCase.indexOf(characters[i])) {
            countOfUniqueChars--;
        }
    }
    return countOfUniqueChars;
}

I just check the index for every character, and if it's different from the original index, there are multiple occurrences.

我只是检查每个字符的索引,如果它与原始索引不同,则出现多次。

回答by Mike B

You could make a new String, called uniqueCharsand initialize it to "". Iterate over the characters in the Stringyou're checking. If uniqueChars.contains(charToCheck)is false, then append that character to uniqueChars. At the end of the loop, uniqueChars.length()will tell you how many unique characters you had. It's ugly and inefficient but it should work.

您可以创建一个新的String,调用uniqueChars并将其初始化为"". 迭代String您正在检查的字符。如果uniqueChars.contains(charToCheck)false,则将该字符附加到uniqueChars. 在循环结束时,uniqueChars.length()会告诉你你有多少个独特的角色。它丑陋且效率低下,但它应该可以工作。

回答by Alexandre Santos

Use a vector.

使用向量。

    char[] letters = new char[26];
    for (char c : letters)
    {
        letters[c]=0;
    }

Then for every letter found, increment the position in the vector. If any entries have a counter greater than 1 then you have repeats

然后对于找到的每个字母,增加向量中的位置。如果任何条目的计数器大于 1,则您有重复

回答by George Irimiciuc

How about put it into an array, sort it alphabetically, then apply your logic(comparing adjacents)?

把它放入一个数组,按字母顺序排序,然后应用你的逻辑(比较相邻元素)怎么样?

v  = sort(v);//your sort method

int count = 0;
for (int i = 0;i< lengthText-1; i++) 
{ if v[i] == v[i + 1]  {
        i++;
    } else {
        count++;
    }
}

By the way, your program doesn't work because you do i == lengthText-1in your for loop.

顺便说一下,您的程序无法运行,因为您i == lengthText-1在 for 循环中运行。

回答by Christopher Francisco

use an ArrayListand add a charactar if not in there already:

使用 anArrayList并添加一个字符(如果不在那里):

list = new ArrayList<String>();
for ( /*   */ ) {  // same for loop you wrote
      String character = (String) text.charAt(i);

       if(!list.contains(character)) {  // note the '!'
            list.add(character);
       }
}

// and finally
int quantity = list.size();

回答by Brian S

How about this one? It's a regex solution rather than a loop:

这个怎么样?这是一个正则表达式解决方案,而不是一个循环:

public static int countUniqueCharacters(String input)
{
    String unique = input.replaceAll("(.)(?=.*?\1)", "");
    return unique.length();
}

If the program needs to be case-insensitive, you can use this instead:

如果程序需要不区分大小写,您可以使用它:

public static int countUniqueCharacters(String input)
{
    String unique = input.replaceAll("(?i)(.)(?=.*?\1)", "");
    return unique.length();
}

You could make this a single-line method with return input.replaceAll(...).length();

您可以将其设为单行方法 return input.replaceAll(...).length();

Regex Explained:

正则表达式解释:

  • .matches any character
  • (...)creates a capturing group, to be referenced later
  • (?=...)creates a lookahead, to look forwards in the input
  • .*?matches anything between the character and its match (non-greedy matching)
  • \\1matches the first capturing group
  • (?i)sets the case-insensitive flag
  • .匹配任何字符
  • (...)创建一个捕获组,稍后引用
  • (?=...)创建一个前瞻,在输入中向前看
  • .*?匹配字符与其匹配之间的任何内容(非贪婪匹配)
  • \\1匹配第一个捕获组
  • (?i)设置不区分大小写的标志

So, the regex will look for any character which has a duplicate later in the string, and then replaceAllwill replace it with the empty string. So, an input like "cabbacbdbadbcabdaadcb"becomes "adcb"(keeping the last of each unique character). Then, with a string containing unique characters, that string's length is the answer.

因此,正则表达式将查找字符串中稍后有重复的任何字符,然后replaceAll将其替换为空字符串。因此,输入就像"cabbacbdbadbcabdaadcb"变成"adcb"(保留每个唯一字符的最后一个)。然后,对于包含唯一字符的字符串,该字符串的长度就是答案。

If, for some reason, you needed the unique-character string andyou needed it in the original order, you would have to reverse the original string before stripping away duplicate characters (and then reverse it again when you're done). This would require either a third-party library, StringBuffer, or a loop.

如果出于某种原因,您需要唯一字符串并且需要按原始顺序使用它,则必须在去除重复字符之前反转原始字符串(然后在完成后再次反转它)。这将需要第三方库StringBuffer、 或循环。

回答by Wonil

Same logic with @Alexandre Santos, but with working sample codes. Complexity is O(N). Works only with alphabetical string without space, numeric or special characters.

与@Alexandre Santos 的逻辑相同,但使用示例代码。复杂度是 O(N)。仅适用于没有空格、数字或特殊字符的字母字符串。

This also can be used as counting sort.

这也可以用作计数排序

public class CountChars 
{
    public static int countUniqCharacters(String str) {
        int[] counts = new int['z' - 'a' + 1];
        char[] arr = str.toLowerCase().toCharArray();

        for (char c: arr) {
            counts[c - 'a']++;
        }

        int unique = 0;
        for (int i: counts) {
            if (i > 0)
                unique++;
        }

        return unique;
    }

    public static void main(String[] args) {
        System.out.println("Unique char in " + args[0] 
                + " is " + CountChars.countUniqCharacters(args[0]));
    }
}

回答by Yogi

Here is the program for how to write a file, how to read the same file, and how count number of times the particular character repeated:

这是关于如何写入文件、如何读取同一文件以及如何计算特定字符重复次数的程序:

package filereadexple;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;

        /*
         * This is a program here I am creating a file by using "filewriter" 
         * and it is named as count.char and I am reading a same file and 
         * then how count number of times the particular character repeated.
         */

public class CountNoOfPartChar {

    public static void main (String args[]){

        File file = new File ("count.char");

        try{
            FileWriter fw = new FileWriter("count.char");
            fw.write("In Xanadu did Kubla Khan");
            fw.write("\r\n");
            fw.write("A stately pleasure-dome decree:");
            fw.write("\r\n");
            fw.write("Where Alph, the sacred river, ran");
            fw.write("\r\n");
            fw.write("Through caverns measureless to man");
            fw.write("\r\n");
            fw.write("Down to a sunless sea.");
            fw.close();
            FileInputStream fis = new FileInputStream(file);
            int i;
            int occurs = 0;
            char current;
            while ((i=fis.available()) > 0){
                current = (char)fis.read();
                if(current == 'a'){
                    occurs++;
                }
            }
            System.out.println("The number of particular character repeated is : " + occurs);
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}

回答by thripura

public class CharacterCount {
    public static void main(String[] args) {
        String s = "aaabbbcccddd";
        String t="";
        int count = 0;

        //Loop to find unique characters in a string and add it to new string called t
        //if a character is not found in a string indexOf returns -1
        for (int i = 0; i < s.length(); i++) {
            if (t.indexOf(s.charAt(i))==-1) t+=s.charAt(i);
        }

        //For every character new string t , loop though s find the count and display
        for (int i = 0; i < t.length(); i++) {
            count = 0;
            for (int j = 0; j < s.length(); j++) {
                if (t.charAt(i) == s.charAt(j)) count++;
            }
            System.out.println(t.charAt(i) + " " + count);
        }
    }
}

回答by Kiran Patil

      public class Main {
     public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
getvalues(s1);
   }
         public static void getvalues(String s1) {
String s2 = s1.toLowerCase();
StringBuffer sb = new StringBuffer(s2);
int l = sb.length();
int count = 0;
for (int i = 0; i < l; i++) {
  count = 0;
  for (int j = i + 1; j < l; j++) {
    if (sb.charAt(i) == sb.charAt(j)) {
      sb.deleteCharAt(j);
      count++;
      j--;
      l--;
    }
  }
  if (count > 0) {
    sb.deleteCharAt(i);
    i--;
    l--;
  }
}
if (sb.length() == 0) {
  System.out.println(-1);
} else
  System.out.println(sb.length());
 }
 }