Technical Article

Remove multiple whitespace from a string

,

Simple enough routine that I've had to write I don't know how many times in different languages. It does what it says in the title i.e. kills multiple occurences of the whitespace character, leaving one behind to tell the tale.

CREATE   FUNCTION [dbo].[cleanString] (@s varchar(50))  
RETURNS varchar(50)
AS
BEGIN 
declare @i int, @l int
declare @t varchar(50), @d varchar(50)
   select @s=LTRIM(RTRIM(@s))
   select @i=CHARINDEX('  ',@s) -1
   if @i<1 return @s
   set @t=''
   while @i>0
   begin
set @d=LEFT(@s,@i)
set @t = @t + ' ' + @d
        set @l=LEN(@s)
set @s=LTRIM(right(@s,@l-@i-2))
set @i=CHARINDEX('  ',@s)-1
   end
RETURN ( ltrim(@t + ' ' + @s) )     
END

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating