[编程题]查找字符串'10,A,B' 中逗号','出现的次数cnt
• 热度指数：12357 时间限制：C/C++ 1秒，其他语言2秒 空间限制：C/C++ 32M，其他语言64M
• 算法知识视频讲解

`SELECT (length("10,A,B")-length(replace("10,A,B",",","")))/length(",") AS cnt`

`SELECT 2 AS cnt`

``select 2 as cnt;``

`select length('10,A,B') -length(replace('10,A,B',",",""))`
length():统计字符串长度
replace(字符串，“需要替换的子串”，“用于替换子串的字符串”）

char_length（）: 统计的是字符长度，而length()函数统计的是字符串的字节长度，所以length('中')在utf8下的结果是3，而char_length('中')的结果仍然是1.

select char_len('A,10,B')-char_len(insert((insert('10,A,B',3,1,'')),4,1,''));

SELECT
length( '10,A,B') - length(REPLACE( '10,A,B',',',''));

1.通过length函数获得字符串的长度：length( '10,A,B')
2.通过replace函数，用空字符替代掉所求字符，并获得替代后的字符串长度： length(REPLACE( '10,A,B',',','')
3.两者相减，获得所求字符出现的次数：length( '10,A,B') - length(REPLACE( '10,A,B',',',''));

`select (length("10,A,B") - length(replace("10,A,B", ",", "")))  as cnt;`

①巧用length函数和replace，length函数计算字符串的长度，length("10,A,B")算出整个字符串的长度。
②使用replace将 , 替换为空，那么整个字符串减少的长度等于 , 的长度，两者相减就是 , 出现的次数。

`select length('10,A,B') - length(replace('10,A,B',",","")) as cnt`

```select length('10,A,B') -length(replace('10,A,B',",",""))
```

```select (length("10,A,B")-length(replace("10,A,B",",",""))) as cnt
```

```select (length('10,A,B')-length(REPLACE('10,A,B',",","")))/length(',') AS cnt
```

【题解参考@wasrehpic】SQLite 中没有直接统计字符串中子串出现次数的函数，因此大家都用length()函数与replace()函数的结合解决了统计子串出现次数的问题。

SELECT (LENGTH('10,A,B') - LENGTH(REPLACE('10,A,B',',','')))/LENGTH(',')

select length('10,A,B')-length(replace('10,A,B',",","")) as cnt;
# length() , replace()

select length('10,A,B')-length(replace('10,A,B',",","")) as cnt;

SELECT (length("10,A,B")-length(replace("10,A,B",",","")))/l

select (length('10,A,B' )-length(replace('10,A,B' ,',',''))) as cnt

select (length("10,A,B")-length(replace("10,A,B",",","")))/length(",") as cnt

28条回答 9011浏览

# 通过挑战的用户

• 2020-01-21 14:59:59
• 2020-01-21 11:02:12
• 2020-01-21 10:43:00
• 2020-01-20 15:29:05
• 2020-01-19 18:14:08

# 相关试题

• 扫描二维码，关注牛客网

• 下载牛客APP，随时随地刷题