Remove multiple whitespace from a string

  • I just read the script posted on 9/20/04 for removing multiple whitespace from a string. Wouldn't this be an easier, cleaner, soulution?

    CREATE FUNCTION [dbo].[cleanString1] (@inString varchar(50)) 

    RETURNS varchar(50)

    AS

    BEGIN

       declare @multiSpaceFound int

       declare @tmpString varchar(50)

       set @tmpString = LTRIM(RTRIM(@inString))

       set @multiSpaceFound = CHARINDEX('  ',@tmpString)

       while (@multiSpaceFound > 0)

       begin

     set @tmpString = Replace(@tmpString,'  ', ' ')

            set @multiSpaceFound = CHARINDEX('  ',@tmpString)

       end

    RETURN @tmpString

    END

  • How much faster is it than the other version?

    Cleaner but slower doesn't do much for any of us.

    Could you do some test and report back to the board??

  • Use the 'REPLACE' function

    declare @Words varchar(255)

    select @Words = 'This is a test of the REPLACE FUNCTION'

    select replace(@words,' ', '')

  • It wouldn't work >>

    declare @Words varchar(255)

    select @Words = 'This is a test of the REPLACE FUNCTION'

    select replace(@words,' ', ' ')

    This is a test of the REPLACE FUNCTION

    you need to run it as long as their are ' ' occurances.

  • can someone tell me why the double white spaces are removed from the posts??

  • Remi:

    I suspect it's simply an "HTML" thing. HTML ignores whitespace (well, at least more than 1 whitespace). You could enter "Hello World" with 100 spaces in between the 2 words, but when it's displayed in HTML, it would look as if 1 space seperated them.

  • Thanx for the reminder... havn't coded anything in html for 8 months now :-(..

    In answer of Al Matthews, if you try this you'll see the problem

    Declare @Words varchar(255)

    select @Words = 'This is a            test of the REPLACE FUNCTION'

    select replace(@words,'  ', ' ')

    gives : This is a      test of the REPLACE FUNCTION

    instead of 'This is a test of the REPLACE FUNCTION'

  • Yep, that's why I have the REPLACE function within a WHILE loop.

Viewing 8 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic. Login to reply