Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the number of occurrences of a char in a String?

Tags:

java

string

I have the string

a.b.c.d 

I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.

(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).

like image 627
Bart Avatar asked Nov 09 '08 14:11

Bart


People also ask

How do you count a string occurrence in a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you count characters in a string in Python?

In Python, you can get the length of a string str (= number of characters) with the built-in function len() .


1 Answers

How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop.

int count = line.length() - line.replace(".", "").length(); 
like image 200
Andreas Wederbrand Avatar answered Oct 18 '22 11:10

Andreas Wederbrand