Count number of blanks in a string

Accepted Solution Solved
Reply
Contributor
Posts: 21
Accepted Solution

Count number of blanks in a string

Hello!

 

I have a quick question I hope you can answer:

 

There is a string "The red car jumped over the bridge."  How do I write a statement that counts the number of blanks in a string?

 

Thank you so much!


Accepted Solutions
Solution
‎04-11-2016 09:46 PM
Contributor
Posts: 21

Re: Count number of blanks in a string

Hi Tom,

 

Thank you greatly for variaty of solutions Smiley Happy

 

The third one is my favorate, because it can count leading and trailing blanks too!

 

Best Wishes Smiley Happy

 

 

View solution in original post


All Replies
Regular Contributor
Posts: 228

Re: Count number of blanks in a string

Contributor
Posts: 21

Re: Count number of blanks in a string

I will try this!  Thank you Wong!

Super User
Posts: 5,497

Re: Count number of blanks in a string

n_blanks = length(var) - length(compress(var));

Contributor
Posts: 21

Re: Count number of blanks in a string

Posted in reply to Astounding

Hi Astounding,

 

Works great for leading blanks and blanks between words!  I am also trying to count trailing blanks in a string too, if possible. 

 

 

Thank you so much Smiley Happy

 

 

Super User
Super User
Posts: 7,039

Re: Count number of blanks in a string

In the past I always used 

 

length(string)-length(compress(string,' '))

But now with new functions like COUNTC() you could also use

 

 

countc(trim(string),' ')

You need to be careful when counting spaces in variables because SAS stores all character variables as fixed length strings that are padded with spaces.  So if you did this:

data _null_
  c1=countc("The red car jumped over the bridge.",' ');
  put c1=;
run;

You would get 6, but if you did this:

data _null_;
  length x $50;
  x="The red car jumped over the bridge.";
  c1=countc(x,' ');
  put c1=;
run;

You would get 21.

 

Solution
‎04-11-2016 09:46 PM
Contributor
Posts: 21

Re: Count number of blanks in a string

Hi Tom,

 

Thank you greatly for variaty of solutions Smiley Happy

 

The third one is my favorate, because it can count leading and trailing blanks too!

 

Best Wishes Smiley Happy

 

 

Super User
Super User
Posts: 7,942

Re: Count number of blanks in a string

Hi,

 

For future reference, please mark the post of the person who correctly answered your question as the correct answer, not a reply to it that you have posted.  This helps keep acurate answers below the questions, and gives some credit to the poster who answered the question. Also noted on the post "Sum digits of a string".

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 7 replies
  • 967 views
  • 3 likes
  • 5 in conversation