Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of times a particular character appears in a string

Tags:

sql-server

Is there MS SQL Server function that counts the number of times a particular character appears in a string?

like image 708
Old Man Avatar asked Mar 20 '12 14:03

Old Man


People also ask

How do you count how many times a character appears 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 find occurrences of a 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 number of times a letter appears in a string Java?

In the Java program to count total number of occurrences of each character in a String using char array, given String is converted to char array then you need to iterate the array starting from first index and check if that character is found again in the char array. If yes then increase the count.


2 Answers

There's no direct function for this, but you can do it with a replace:

declare @myvar varchar(20) set @myvar = 'Hello World'  select len(@myvar) - len(replace(@myvar,'o','')) 

Basically this tells you how many chars were removed, and therefore how many instances of it there were.

Extra:

The above can be extended to count the occurences of a multi-char string by dividing by the length of the string being searched for. For example:

declare @myvar varchar(max), @tocount varchar(20) set @myvar = 'Hello World, Hello World' set @tocount = 'lo'  select (len(@myvar) - len(replace(@myvar,@tocount,''))) / LEN(@tocount) 
like image 168
Jon Egerton Avatar answered Sep 23 '22 02:09

Jon Egerton


Look at the length of the string after replacing the sequence

declare @s varchar(10) = 'aabaacaa' select len(@s) - len(replace(@s, 'a', '')) >>6 
like image 44
Alex K. Avatar answered Sep 22 '22 02:09

Alex K.