## Remove only the second space from a string

Solved
Occasional Contributor
Posts: 19

# Remove only the second space from a string

How can I remove only the 2nd space in a string?

Accepted Solutions
Solution
‎06-27-2016 01:54 AM
Super User
Posts: 10,846

## Re: Remove only the second space from a string

```data _null_;
x='xxx yyy zzz';
call scan(x,3,p,l,' ');
want=substr(x,1,p-2)||substr(x,p);
put x= want=;
run;

```

All Replies
Super User
Posts: 6,903

## Re: Remove only the second space from a string

There may be easier ways.

It may be that this is not what you really want.  Remember, you are only shifting text over since the length of a character variable is fixed.

You may be better served by the COMPBL function.

WIth all that in mind, here is a way to approach what you asked for:

data want;

set have;

blanks=0;

if string > ' ' then do i=1 to length(string) until (blanks=2);

if substr(string, i, 1)=' ' then blanks + 1;

end;

if blanks=2 then string = substr(string, 1, i-1) || substr(string, i+1);

run;

I also tried looking at CALL SCAN, but didn't find an approach that seemed like it would work.

Posts: 5,614

## Re: Remove only the second space from a string

Given the string

AsBsCssD

where s is a space, do you want

AsBCssD  (second space of the string removed)

or

AsBsCsD  (double space replaced by single space) ?

PG
Posts: 4,779

## Re: Remove only the second space from a string

What does "2nd space" mean? The 2nd occurence of a space or just don't have consecutive spaces?

For "not consecutive spaces" I'd use function "compbl()"

Solution
‎06-27-2016 01:54 AM
Super User
Posts: 10,846

## Re: Remove only the second space from a string

```data _null_;
x='xxx yyy zzz';
call scan(x,3,p,l,' ');
want=substr(x,1,p-2)||substr(x,p);
put x= want=;
run;

```
🔒 This topic is solved and locked.