Spaces in strings.. Check this out

  • What this does. Someone asked at another forum if there was a way to replace multiple spaces in a string with just one space. This works good. Please feel free to modify, change and add to this code.

    declare @r varchar(10)

    declare @LenWithSpaces INT

    declare @LenWithoutSpaces INT

    declare @NumOrSpacesToRemove INT

    SET @r = 'A B'

    SELECT @LenWithSpaces = LEN(@r)

    SELECT @LenWithoutSpaces = LEN(REPLACE(@r,' ',''))

    SELECT @NumOrSpacesToRemove = ((@LenWithSpaces - @LenWithoutSpaces)-1)

    SELECT @LenWithSpaces

    SELECT @LenWithoutSpaces

    SELECT @NumOrSpacesToRemove

    SELECT REPLACE(@r,SPACE(@NumOrSpacesToRemove),'')

    William O'Malley

  • Yes, that will work if the string has just one set of multiple spaces. eg.

    SET @r = 'A  B'
    

    But it has no effect if there's 2 or more sets of multiple spaces:

    SET @r = 'A  B  C'
    

    Cheers,

    - Mark


    Cheers,
    - Mark

  • 
    
    Declare @r Varchar(100)
    Set @r=' a b c d e '
    While CharIndex(' ',@r)>0
    Set @r=Replace(@r,' ',' ')
    Select @r
  • quote:


    
    
    Declare @r Varchar(100)
    Set @r=' a b c d e '
    While CharIndex(' ',@r)>0
    Set @r=Replace(@r,' ',' ')
    Select @r

    Nice...

    Will

Viewing 4 posts - 1 through 4 (of 4 total)

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