PV-WAVE Foundation > Programmer Guide > Working with Text > Removing White Space from Strings
Removing White Space from Strings
The STRCOMPRESS and STRTRIM functions remove unwanted white space (tabs and spaces) from a string. This can be useful when reading string data from arbitrarily formatted strings.
STRCOMPRESS returns a copy of its string argument with all white space replaced with a single space, or completely removed. It has the form:
result = 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. Use of the Remove_All keyword causes white space to be completely eliminated. For example:
; Create 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:
> This is a poorly spaced sentence.<
>Thisisapoorlyspacedsentence.<
STRTRIM returns a copy of its string argument with leading and/or trailing white space removed. It has the form:
result = 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 are removed if it is equal to 2.
As an 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:
>  This string has leading and trailing white space<
>This string has leading and trailing white space   <
>This string has leading and trailing white space<
When processing string data, it is often useful to be able to remove leading and trailing white space and shrink any white space in the middle down to single spaces. STRCOMPRESS and STRTRIM can be combined to handle this:
; 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:
>Yet another poorly spaced sentence.<