SAS String Functions: A Practical Guide

Formulas & functions · Updated November 22, 2026

In SAS, string functions are character functions used to inspect, extract, join, clean, and transform text; there is no single function called “string function.” Common choices include SUBSTR for a section of text, SCAN for a delimited word, STRIP for removing edge blanks, and CATX for joining values with a separator.

What SAS Means by a String

SAS generally calls text a character value. Character variables are declared with a length, such as $20, and that length is established when SAS compiles a DATA step. A variable assigned the value North in a 20-character field still occupies a field of that declared length; the unused space is padded with blanks. This fixed-width behavior is one reason SAS text functions can behave differently from string operations in languages that store text as variable-length values.

Character values can contain names, codes, addresses, dates stored as text, or other material that is not yet a SAS numeric value. A date that looks like 2026-11-03, for example, is still text if it is held in a character variable. String functions can clean or split that text, but they do not automatically convert it into a SAS date value. Conversion requires an appropriate informat or other date-handling step.

These functions are used most often in DATA steps, but many are also available in PROC SQL and other SAS contexts. Check the documentation for a particular function if using it in a special procedure or an older SAS release, since availability and details can vary by context.

How SAS Handles Blanks and Lengths

Trailing blanks matter because character values are padded to their declared length. SAS provides several length functions to answer different questions. LENGTH reports the length through the last nonblank character, while LENGTHN returns zero for a blank value. LENGTHC reports the allocated character length, including trailing blanks. For a variable declared as $12 containing Oak, these functions can therefore describe different things: meaningful text length, meaningful text length with a special blank result, or storage length.

This distinction is useful when validating data. A blank character value can have a storage length even though it contains no meaningful text. If a check should treat an all-blank field as empty, LENGTHN is often a clearer test than LENGTH. If the question is how wide the variable was defined, use LENGTHC.

Character length is also not always identical to the number of visible symbols. In multibyte encodings, some characters can occupy more than one byte. SAS has K-functions, such as KLENGTH and KUPCASE, designed for character-aware operations in multibyte data. The right function depends on the session encoding and the way the data is stored; do not assume byte counts and displayed-character counts always match.

Essential SAS String Functions

The best function depends on the operation. These commonly used functions cover many routine cleaning and extraction tasks:

  • SUBSTR(source, position, length) returns part of a character value. Positions begin at 1, not 0. For example, SUBSTR('AB-123', 4, 3) returns 123.
  • SCAN(source, n, delimiters) returns the nth word or token separated by specified delimiters. For example, SCAN('Lee,Jordan', 2, ',') returns Jordan.
  • INDEX(source, target) returns the position of the first occurrence of a target, or 0 if it is not found. FIND offers optional modifiers, including one for case-insensitive searching.
  • STRIP removes leading and trailing blanks. TRIM removes trailing blanks, while LEFT and RIGHT move text toward the left or right edge of its field.
  • COMPBL reduces multiple consecutive blanks to one. COMPRESS removes specified characters, or can be configured with modifiers to keep selected character classes.
  • UPCASE, LOWCASE, and PROPCASE change letter case. Case conversion is useful for standardization, but it should not be applied blindly to values where capitalization carries meaning.
  • TRANWRD replaces occurrences of a specified character string with another string. It is a literal text replacement, not a regular-expression search.

For example, to keep only digits from a phone field, the DATA step expression COMPRESS(phone, , 'kd') uses the keep modifier and digit class. Test such cleaning against real input: it may remove punctuation as intended, but it will not decide whether a country code or extension should be preserved.

Joining Text with CAT Functions

SAS has a family of concatenation functions. CAT joins character arguments, CATT trims trailing blanks from arguments before joining, and CATS trims both leading and trailing blanks. CATX also trims the arguments and inserts a delimiter between nonblank values. These functions help avoid a common nuisance: fixed-width padding creating unwanted gaps in a combined value.

Suppose a DATA step has first and last name variables. To create a display name separated by one blank, use CATX(' ', first, last). If one name is blank, CATX avoids adding a separator for that missing component. By contrast, concatenating values with the || operator can preserve padding and may produce unexpected spacing unless the inputs are trimmed deliberately.

Define the output length before assigning a combined value, especially if the result may be longer than the length SAS would otherwise assign. For example:

data want;
    set have;
    length full_name $60;
    full_name = catx(' ', first, last);
run;

The chosen length should be large enough for the expected result but not arbitrary: an undersized character variable can truncate values. Consider the maximum source lengths and the delimiter when deciding how wide the result must be.

Choosing a Function for a Task

Start by describing the operation rather than searching for a generic “string function.” For splitting a value into delimited pieces, consider SCAN; for taking characters at known positions, use SUBSTR; for finding text, use INDEX or FIND; and for joining cleaned pieces, use CATX. If the task is removing or normalizing characters, choose between COMPRESS, COMPBL, and TRANWRD according to what should change.

For example, a code such as US-4582 has a stable layout: if the country code is always the first two characters and the number always follows the hyphen, positional extraction may be suitable. If the separator or number of pieces can vary, tokenizing with SCAN is usually more adaptable. Delimiters should be specified explicitly when they are part of the data format; otherwise, a function may split on characters the analyst did not intend.

Also decide whether comparison should be case-sensitive. INDEX searches for a matching character sequence, while FIND can use a modifier for case-insensitive matching. An alternative is to standardize case first, but modifying the stored value may be undesirable if its original capitalization must be retained. Keep a cleaned or comparison value separate when preserving source text matters.

Working Example: Clean and Split a Value

Suppose a field contains a value such as Seattle, WA , with optional blanks around the city and state. A DATA step can remove edge blanks, extract the two comma-separated pieces, and create a normalized display value:

data want;
    set have;
    length city $40 state $2 location $45;
    cleaned = strip(city_state);
    city = strip(scan(cleaned, 1, ','));
    state = strip(scan(cleaned, 2, ','));
    location = catx(', ', city, state);
run;

The explicit lengths make the intended output capacity visible. STRIP removes leading and trailing blanks from the original value and from each extracted piece. SCAN uses the comma as its delimiter, and CATX rebuilds the result with a comma and one blank. This example assumes a comma is present and that the state field fits in two characters. Production code should check or handle rows that are missing a comma, contain extra commas, or have a longer value than expected.

For a simple check that a cleaned value contains a state abbreviation, an expression such as FIND(UPCASE(cleaned), 'WA') can make the search insensitive to capitalization. That does not establish that the text is a valid location: it only finds the characters. Validation rules, such as checking against a controlled list of state codes, are a separate task.

Common Problems and How to Avoid Them

  • Unexpected spaces: SAS padding can make concatenated values look separated by many blanks. Use STRIP or the appropriate CAT-family function, and inspect the output in a way that makes trailing blanks apparent.
  • Truncated results: A character variable has a fixed length. Declare a sufficient length before assignment, and review the log for notes about values being truncated.
  • Wrong position: SAS character positions start at 1. A substring beginning at position 1 includes the first character; position 0 is not the way to request it.
  • Missing delimiter: SCAN can return a blank when the requested token is absent. Check that the expected number of fields exists before relying on the extracted result.
  • Confusing text with numbers: A character string containing digits is not automatically numeric. Use an informat with INPUT to convert character text to a numeric value, and use PUT with an appropriate format to create formatted character output from a numeric value.
  • Changing meaning while cleaning: Removing punctuation or changing case can alter identifiers, product codes, or names. Preserve the original field when the transformation is irreversible or when audits require source values.

A useful debugging practice is to create a temporary output that includes the original value, the cleaned value, and the extracted pieces. Review normal cases and edge cases together. This often reveals whether the issue is blank padding, an unexpected delimiter, a short input value, or an assumption about the data format.

Character Functions in DATA Steps and PROC SQL

Many SAS character functions can be used in both DATA step expressions and PROC SQL expressions, but the surrounding syntax is different. A DATA step assignment uses a statement such as city = strip(city_text);. In PROC SQL, the same kind of expression appears in a query, for example select strip(city_text) as city. The function name and purpose may be familiar, but aliases, missing-value handling, and output-column attributes depend on the procedure context.

When a result is written to a new DATA step variable, SAS determines attributes such as type and length as the step is compiled. Place a LENGTH statement before the assignment when you need to control the output width. In SQL, inspect the resulting column type and length when creating a table or exporting results; a transformation that looks correct in a query can still produce an unsuitable output attribute for later use.

There is no need to convert every character value to another type merely to clean it. Keep identifiers as character when leading zeros matter: converting a code such as 0047 to numeric would lose those zeros unless they are restored through formatting. Convert only when the value is genuinely numeric or date data and the downstream operation requires that type.

Frequently Asked Questions

What is the SAS function for strings?
SAS has many character functions rather than one general string function. Use SUBSTR for a substring, SCAN for a delimited token, STRIP to remove edge blanks, or CATX to join values with a delimiter.

How do I remove spaces from a SAS character variable?
Use STRIP to remove leading and trailing blanks, COMPBL to reduce repeated blanks within text, or COMPRESS to remove specified characters. Choose based on whether internal spaces should remain.

What is the difference between LENGTH and LENGTHN in SAS?
Both measure text through its last nonblank character, but LENGTHN returns 0 for an all-blank value. LENGTH returns 1 for an all-blank argument. Use LENGTHC when you need the allocated character length including trailing padding.

Does SAS SUBSTR start at zero or one?
It starts at 1. For example, SUBSTR('ABCDE', 1, 2) returns AB, and SUBSTR('ABCDE', 3, 2) returns CD.

Why is my SAS text result cut off?
Character variables have fixed lengths, and a result assigned to a variable that is too short can be truncated. Declare an adequate length before the assignment and check the SAS log for truncation notes.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.