Showing posts with label Count. Show all posts
Showing posts with label Count. Show all posts

Wednesday, March 4, 2009

Count Words in String

Started with the logic in Oracle PL/Sql Programming by Steven Feuerstein. Changed some names to make sense to me, added some comments, and tweaked a few things.
Create or Replace Function 
WordCount (v_InpStr In Varchar2)
Return Pls_Integer
As
v_WordCnt Pls_Integer := 0;
v_StrLen Pls_Integer := Nvl(Length(v_InpStr),0);
In_A_Word Boolean;

Begin
For v_Ctr in 1..v_StrLen + 1
Loop
/*----------------------------------------*/
/* if a blank or at the end of the string */
/*----------------------------------------*/

If Substr(v_InpStr, v_Ctr, 1) = ' '
or v_Ctr > v_StrLen
Then
/*---------------------------------------*/
/* If a space is found after a word then */
/* bump the count, and reset the flag */
/* (handles multiple spaces) */
/*---------------------------------------*/

If In_A_Word
Then
v_WordCnt := v_WordCnt +1 ;
In_A_Word := False;
End If;
Else
/*--------------------------------------*/
/* The current character is not a space */
/*--------------------------------------*/

In_A_Word := True;
End If;
End Loop;

Return v_WordCnt;
End;
/
Select Street_Address
, WordCount(Street_Address)
As
Words
From Locations
Where Rownum < 6;

SQL> Desc WordCount
FUNCTION WordCount RETURNS BINARY_INTEGER
Argument Name Type In/Out Default?
------------- -------- ------ --------
INPSTR VARCHAR2 IN

SQL> Grant Execute on WordCount to Scott;

Grant succeeded.