Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count string occurrence in string?

How can I count the number of times a particular string occurs in another string. For example, this is what I am trying to do in Javascript:

var temp = "This is a string."; alert(temp.count("is")); //should output '2' 
like image 362
TruMan1 Avatar asked Oct 24 '10 18:10

TruMan1


People also ask

How do you find the number of occurrences in a string?

count() One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.

How do you count occurrences of each character in a string?

In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.

How do you find the occurrence of a string in Python?

Iterate the entire string for that particular character and then increase the counter when we encounter the particular character. Using count() is the most conventional method in Python to get the occurrence of any element in any container. This is easy to code and remember and hence quite popular.


1 Answers

The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice:

var temp = "This is a string.";  var count = (temp.match(/is/g) || []).length;  console.log(count);

And, if there are no matches, it returns 0:

var temp = "Hello World!";  var count = (temp.match(/is/g) || []).length;  console.log(count);
like image 84
Rebecca Chernoff Avatar answered Sep 27 '22 18:09

Rebecca Chernoff