特定字符出现在字符串中的次数 [英] Number of times a particular character appears in a string

查看:29
本文介绍了特定字符出现在字符串中的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 MS SQL Server 函数可以计算特定字符在字符串中出现的次数?

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

推荐答案

没有直接的功能,但你可以通过替换来实现:

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.

额外:

以上可以扩展为通过除以正在搜索的字符串的长度来计算多字符字符串的出现次数.例如:

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)

这篇关于特定字符出现在字符串中的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆