Published on :
Data Manipulation CREATION_INTERNE

Using COUNT and COUNTC functions

This code is also available in: Deutsch Español Français
Awaiting validation
The script contains two DATA step blocks. The first uses the COUNTC function to count the number of occurrences of a specific character ('a') in a string. The second block uses the COUNT function to count the number of occurrences of a substring ('dog') in another string. The results are displayed in the SAS© log.
Data Analysis

Type : CREATION_INTERNE


The data used are literal character strings defined directly in the DATA steps via variable assignments.

1 Code Block
DATA STEP Data
Explanation :
This DATA step block initializes a 'long' variable with a character string. The COUNTC function is then used to count all occurrences of the character 'a' (including duplicates) in the 'long' string. The result is stored in 'num_a' and displayed in the SAS log.
Copied!
1DATA _null_ ;
2 long='a b c d a e d a e t g d a c s' ;
3 num_a=countc(long,'a') ;
4 put num_a= ;
5RUN ;
2 Code Block
DATA STEP Data
Explanation :
This DATA step block initializes a 'long' variable with another character string. The COUNT function is used to count occurrences of the 'dog' substring in the 'long' string. It is important to note that COUNT counts occurrences as distinct words by default, but the function can be more flexible depending on delimiters. Here, 'bigdog' will not be counted as an occurrence of 'dog' unless specific delimiters are used. The result is stored in 'num_dog' and displayed in the SAS log.
Copied!
1DATA _null_ ;
2 long='dog cat rat bat dog camel dingo snake bigdog' ;
3 num_dog=count(long,'dog') ;
4 put num_dog= ;
5RUN ;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.