开发者

Find occurrences of characters in a Java String [duplicate]

This question already has answers here: How do I count the number of occurrences of a char in a String? (48 answers) Closed 5 years ago.

I would like to count the occurrences of a character in a string, suppose开发者_如何学C I have the string "aaaab", how would i count the amount of a's in it?


Guava's CharMatcher API is quite powerful and concise:

CharMatcher.is('a').countIn("aaaab"); //returns 4


String string = "aaab";
int count = string.length() - string.replaceAll("a", "").length();

instead of "a" use a regex like "[a-zA-Z]" to count all word characters


Try using Apache Commons' StringUtils:

int count = StringUtils.countMatches("aaaab", "a");
// count = 4 


The code looks way easier to read if you don't use regular expressions.

int count = 0;
for(int i =0; i < string.length(); i++)
    if(string.charAt(i) == 'a')
        count++;

count now contains the number of 'a's in your string. And, this performs in optimal time.

Regular expressions are nice for pattern matching. But just a regular loop will get the job done here.


Regular expressions aren't particularly good at counting simple things. Think ant+sledgehammer. They are good at busting complex strings up into pieces.

Anyway, here's one solution the OP is interested in - using a regex to count 'a's:

public class Reggie {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("[^a]*a");
        Matcher matcher = pattern.matcher("aaabbbaaabbabababaaabbbbba");
        int count =  0;
        while(matcher.find()) {
            count++;
        }
        System.out.println(count+" matches");
    }
}

This is a pretty slow way to do it, as pointed out by others. Worse, it isn't the easiest and certainly isn't the most likely to be bug-free. Be that as it may, if you wanted something a little more complex than 'a' then the regex would become more appropriate as the requested string got more complex. For example, if you wanted to pick dollar amounts out of a long string then a regex could be the best answer.

Now, about the regex: [^a]*a

This [^a]* means 'match zero or more non-'a' characters. This allows us to devour non-'a' crud from the beginning of a string: If the input is 'bbba' then [^a]* will match 'bbb'. It doesn't match the 'a'. Not to worry, the trailing 'a' in the regex says, "match exactly one 'a'". So our regex says, "match zero or more non-'a' characters that are followed by an 'a'."

Ok. Now you can read about Pattern and Matcher. The nutshell is that the Pattern is a compiled regular expression. It is expensive to compile a regex so I make mine static so they only get compiled once. The Matcher is a class that will apply a string to a Pattern to see if it matches. Matcher has state information that lets it crawl down a string applying a Pattern repeatedly.

The loop basically says, "matcher, crawl down the string finding me the next occurrence of the pattern. If we find it, increment the counter." Note the character sequences being found by Matcher isn't just 'a'. It is finding sequences like the following: 'a', 'bbba', 'bba', 'ba', etc. That is, strings that don't contain an 'a' except for their last character.


int count = 0;
for (char c : string.toCharArray()) 
    if (c == 'a')
        count++;


A simple loop over the characters would do it.

public int countChars(char c, String s) {
  int result = 0;
  for (int i = 0, n = s.length(); i < n; i++) {
    if (s.charAt(i) == c) {
      result++;
    }
  }
  return result;
}


Here is a really short solution without any extra libraries:

String input = "aaaab";

int i = -1, count = 0;
while( (i = input.indexOf( 'a', i + 1 ) ) != -1 ) count++;

System.out.println( count );


      String searchFor = "a";
      String base = "aaaab";
      int count=0;
      int index =base.indexOf(searchFor);

      while(index!=-1){
          ++count;
          index = base.indexOf(searchFor, index+searchFor.length());
      }

      System.out.println(count);


public static void main(String[] args) {

    Map<Character, Integer> data = new HashMap<Character, Integer>();

    String s = "aaaab";

    char[] chars = s.toCharArray();
    for (char a : chars) {

        if (data.containsKey(a)) {
            int value = data.get(a);
            data.put(a, value + 1);
        } else {
            data.put(a, 1);
        }

    }
    Iterator it = data.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry) it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
    }
}


You can simply use this:

String a = "i am here as junior java programmer";
Set temp = new HashSet();
char[] chararray=a.toCharArray();
Set temp=new HashSet();
for(int i=0;i<chararray.length;i++)
{
    int  count=0;
    for (int j=0;j<chararray.length;j++) {
        if (chararray[i]==chararray[j]) {
            count++;
        }            
    }
    if (temp.add(chararray[i])!=false)
        System.out.println("Character "+chararray[i]+" occur "+count);

}


String s1="parasanna";

StringBuffer sb=new StringBuffer();
boolean print = false;
for (int i=0; i<s1.length(); i++){
    int count=1;
    char c=s1.charAt(i);
    sb.append(c);
    for (int j=1; j<sb.length(); j++) {
        char c2=sb.charAt(j-1);
        if (c==c2) {
            count++;
        }
    }

    System.out.println(c+"=="+count);

}


Here is My Logic ...

public class OccurenceOf_Character {

    public static void main(String[] args) {

        Scanner input=new Scanner(System.in);       
        System.out.println(" Enter a string");

        String str = input.nextLine();      
        System.out.println(" Enter a character");       

        String character=input.next();      
        int l = character.length();

        char c=character.charAt(0);

        int count=0;        
        for(int i=0;i<str.length();i++)
        {
            if(str.charAt(i) == c)
            {
                count=count+1;
            }   
        }

        System.out.println(count); 
    }
}


You could use StringUtils class provided by apache commons. StringUtils.countMatches(String originalString, String subCharacterSequesnce)


Java 8

Approach 1 - Gets the occurrence of a single character

    String sentence = "Aaron ate apples upon a rock";

    long counted = IntStream.range(0, sentence.length())
            .filter(i->sentence.charAt(i) == 'a')
            .count();
    System.out.println("First approach: " + counted);

Approach 2 - Allows the character to be specified

    String sentence = "Aaron ate apples upon a rock";

    BiFunction<String, Character, Long> counter = (s,c) -> {
        return IntStream.range(0, s.length())
                .filter(i->s.charAt(i) == c)
                .count();
    };
    System.out.println("Second approach (with 'a'): " + counter.apply(sentence, 'a'));
    System.out.println("Second approach (with 'o'): " + counter.apply(sentence, 'o'));

Approach 3 - Counts occurrences of all characters

     String sentence = "Aaron ate apples upon a rock";

     Map<Character, Long> counts = IntStream.range(0, sentence.length())
             .mapToObj(i->sentence.charAt(i))
             .collect(Collectors.groupingBy(o->o, Collectors.counting()));      

     System.out.println("Third approach for every character... ");
     counts.keySet().stream()
        .forEach(key -> System.out.println("'" + key + "'->" + counts.get(key)));


public static void main(String[] args) throws IOException
    {
        //String s1="parasanna";
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("enter string:");
        String s1 = br.readLine();
        StringBuffer sb=new StringBuffer(s1);

        while(sb.length() != 0)
        {
           char c = sb.charAt(0);
           int cnt = 0;
           for(int i=0; i< sb.length(); i++)
           {
           if(c == sb.charAt(i))
           {
               cnt++;
               sb.deleteCharAt(i);
               i--;
           }

           }

           System.out.println(c + "     occurance is:" + cnt);
        }

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜