Click or drag to resize

SubStr Function

Extract a substring from a string.

Namespace:  XSharp.RT
Assembly:  XSharp.RT (in XSharp.RT.dll) Version: 2.08
Syntax
 FUNCTION SubStr(
	 cTarget AS USUAL,
	 nStart AS USUAL,
	 nCount AS USUAL
) AS STRING
View Source

Parameters

cTarget
Type: Usual
The string from which to extract a substring.
nStart
Type: Usual
The starting position in <cTarget>.  If <wStart> is positive, it is relative to the leftmost character in <cTarget>.  If <nStart> is negative, it is relative to the rightmost character in <cTarget>.  If <nStart> is zero, a NULL_STRING is returned.
nCount
Type: Usual
The number of characters to extract.  If omitted, the substring begins at <nStart> and continues to the end of the string.  If <nCount> is greater than the number of characters from <nStart> to the end of <cTarget>, the extra is ignored.

Return Value

Type: String
The substring.  If the substring is not present, a NULL_STRING is returned.
Remarks
Substr() is related to the Left() and Right() functions, which extract substrings beginning with leftmost and rightmost characters in <cTarget>, respectively. The Substr(), Right(), and Left() functions are often used with both the At() and RAt() functions to locate either the first and/or the last position of a substring before extracting it.  They are also used to display or print only a portion of a string.
Examples
These examples extract the first and last name from a variable:
X#
cName := "Biff Styvesent"
? Substr(cName, 1, 4)                                // Biff
? Substr(cName, 6)                                        // Styvesent
? Substr(cName, SLen(cName) + 2)
// Null string
? Substr(cName, -9)                                        // Styvesent
? Substr(cName, -9, 3)                                // Sty
This example uses Substr() with At() and RAt() to create a function to extract a file name from a file specification:
X#
? FileBase("c:\prg\myfile.obj")                // myfile.obj
FUNCTION FileBase(cFile)
        LOCAL nPos AS DWORD
        IF (nPos := RAt("\", cFile)) != 0
                cFile := Substr(cFile, nPos + 1)
        ELSEIF (nPos := At(":", cFile)) != 0
                cFile := Substr(cFile, nPos + 1)
        ENDIF
        RETURN cFile
See Also