Whitespace
The STRCOMPRESS and STRTRIM functions are used to remove unwanted white space (tabs and spaces) from a string. This can be useful when reading string data from arbitrarily formatted strings.
Removing All Whitespace
The function STRCOMPRESS returns a copy of its string argument with all white space replaced with a single space or completely removed. It has the form:
S = STRCOMPRESS(String)
where String is the string to be compressed.
The default action is to replace each section of white space with a single space. Setting the REMOVE_ALL keyword causes white space to be completely eliminated. For example,
; Create a string with undesirable white space. Such a string might ; be the result of reading user input with a READ statement. A = ' This is a poorly spaced sentence. ' ; Print the result of shrinking all white space to a single blank. PRINT, '>', STRCOMPRESS(A), '<' ; Print the result of removing all white space. PRINT '>', STRCOMPRESS(A, /REMOVE_ALL), '<'
results in the output:
Removing Leading or Trailing Blanks
The function STRTRIM returns a copy of its string argument with leading and/or trailing white space removed. It has the form:
S = STRTRIM(String[, Flag])
where String is the string to be trimmed and Flag is an integer that indicates the specific trimming to be done. If Flag is 0 or is not present, trailing white space is removed. If it is 1, leading white space is removed. Both trailing and leading white space are removed if Flag is equal to 2. For example:
; Create a string with unwanted leading and trailing blanks. A = ' This string has leading and trailing white space ' ; Remove trailing white space. PRINT, '>', STRTRIM(A), '<' ; Remove leading white space. PRINT, '>', STRTRIM(A,1), '<' ; Remove both. PRINT, '>', STRTRIM(A,2), '<'
Executing these statements produces the output below.
> This string has leading and trailing white space< >This string has leading and trailing white space < >This string has leading and trailing white space<
Removing All Types of Whitespace
When processing string data, STRCOMPRESS and STRTRIM can be combined to remove leading and trailing white space and shrink any white space in the middle down to single spaces.
; Create a string with undesirable white space. A = 'Yet another poorly spaced sentence. ' ; Eliminate unwanted white space. PRINT, '>' STRCOMPRESS(STRTRIM(A,2)), '<'
Executing these statements gives the result below: