Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check how many times string contains character 'g' in eligible string

Tags:

How we can check any string that contains any character how may time.... example: engineering is a string contains how many times 'g' in complete string

like image 210
user1802156 Avatar asked Nov 06 '12 06:11

user1802156


People also ask

How do you find out how many times a character appears in a string?

Use the count() Function to Count the Number of a Characters Occuring in a String in Python. We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string.

How do you check if a string contains a certain character?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.

How many times a string contains another string in Java?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How many times a character appears in a string Java?

Let's start with a simple/naive approach: String someString = "elephant"; char someChar = 'e'; int count = 0; for (int i = 0; i < someString. length(); i++) { if (someString. charAt(i) == someChar) { count++; } } assertEquals(2, count);


1 Answers

I know this is and old question, but there is an option that wasn't answered and it's pretty simple one-liner:

int count = string.length() - string.replaceAll("g","").length()
like image 168
hungariandatabaseprogrammer Avatar answered Oct 09 '22 09:10

hungariandatabaseprogrammer