Solved
Contributor
Posts: 23

# Counting number of characters in a string for each respondent

Hello!

I have a variable which is a string (currently numeric, though I imagine it might be best to change this to a character format) of numbers. I need to create a flag for any responses that have an odd number of characters. This is not a flag for odd numbers but for the number of characters. I need this for each respondent and not for one individual.

My question: How can I create a code for counting the number of characters in a string? (E.g. 102 = 3, 10879 = 5, etc.)  From there, I can create the flag. For some reason I am just struggling with finding the right code for counting what I need.

Thanks!

Accepted Solutions
Solution
‎07-11-2016 10:31 AM
Posts: 5,539

## Re: Counting number of characters in a string for each respondent

Math to the rescue!

``````/* Assuming the numbers are positive integers */
data have;
input number;
datalines;
102
10879
23
543
12
;

data want;
set have;
digits = 1 + int(log10(number));
oddDigits = mod(digits, 2);
run;

proc print; run;``````
PG

All Replies
Posts: 1,270

## Re: Counting number of characters in a string for each respondent

Hi,

data have;
input number;
datalines;
102
10879
23
543
12
;

data want;
set have;
length flag \$8.;
if mod(length(strip(put(number, 8.))),2) ne 0 then flag='odd';
else flag='even';
run;

Super User
Posts: 23,771

## Re: Counting number of characters in a string for each respondent

Functions to the rescue!

Length provides the length of the string.

Mod(num,2) = 0 can be used to test if a number is even or odd. If a number is divisible by 2 it's even otherwise odd.

The code from @stat_sas looks correct.

Solution
‎07-11-2016 10:31 AM
Posts: 5,539

## Re: Counting number of characters in a string for each respondent

Math to the rescue!

``````/* Assuming the numbers are positive integers */
data have;
input number;
datalines;
102
10879
23
543
12
;

data want;
set have;
digits = 1 + int(log10(number));
oddDigits = mod(digits, 2);
run;

proc print; run;``````
PG
Contributor
Posts: 23

## Re: Counting number of characters in a string for each respondent

Thank you so much - this is exactly what I needed.

☑ This topic is solved.