Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Number of characters in a string

681263May 21 2009 — edited May 21 2009
In SQL Server a method that I sometimes use to count a given character in a string is something like:

declare @test table(string varchar(20))
insert into @test
select null union all
select 'abcdcfc ' union all
select 'abcdcfc c '

select
'''' + string + '''' string,
len(string+'ÿ') - len(replace(string+'ÿ', 'c', '')) char_count
from @test

/* string char_count */
/* ---------------------- ----------- */
/* NULL NULL */
/* 'abcdcfc ' 3 */
/* 'abcdcfc c ' 4 */


I can still use the REPLACE function in Oracle to get the job done with something like:

select
'''' || string || '''' string,
length(string) - length(replace(string, 'c', '')) as char_count
from
( select null as string from dual union all
select 'abcdcfc ' from dual union all
select 'abcdcfc c ' from dual
)

/* string char_count */
/* ---------------------- ----------- */
/* NULL NULL */
/* 'abcdcfc ' 3 */
/* 'abcdcfc c ' 4 */

Is there a way to do this better?


Kent Waldrop
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 18 2009
Added on May 21 2009
11 comments
6,872 views