AfxExtractSubString

This global function can be used to extract a substring from a given source string.

BOOL AFXAPI AfxExtractSubString (
   CString& rString,
   LPCTSTR lpszFullString,
   int iSubString,
   TCHAR chSep = '\n'
);

Parameters

  • rString

    • Reference to a CString object that will receive an individual substring.
  • lpszFullString

    • String containing the full text of the string to extract from.
  • iSubString

    • Zero-based index of the substring to extract from lpszFullString.
  • chSep

    • Separator character used to delimit substrings.

Return Value

TRUE if the function successfully extracted the substring at the provided index; otherwise, FALSE.

Remarks

This function is useful for extracting multiple substrings from a source string when a known single character separates each substring. This function searches from the beginning of the lpszFullString parameter each time it is called.

This function will return FALSE if either lpszFullString is set to NULL or the function reaches the end of lpszFullString without finding iSubString+1 occurrences of the specified separator character. The rString parameter will not be modified from its original value if lpszFullString was set to NULL; otherwise, the rString parameter is set to the empty string if the substring could not be extracted for the specified index.

Example

// The following example extracts a series of name, value pairs from a
// given source string:

// Input string consisting of a number of name, value pairs
LPCTSTR lpszSource = _T("\"Name\"=\"John Smith\"\n")
   _T("\"Company\"=\"Contoso, Ltd\"\n\"Salary\"=\"25,000\"");

CString strNameValue; // an individual name, value pair

int i = 0; // substring index to extract
while (AfxExtractSubString(strNameValue, lpszSource, i))
{
   // Prepare to move to the next substring
   i++;

   CString strName, strValue; // individual name and value elements

   // Attempt to extract the name element from the pair
   if (!AfxExtractSubString(strName, strNameValue, 0, _T('=')))
   {
      // Pass an error message to the debugger for display
      OutputDebugString(_T("Error extracting name\r\n"));
      continue;
   }

   // Attempt to extract the value element from the pair
   if (!AfxExtractSubString(strValue, strNameValue, 1, _T('=')))
   {
      // Pass an error message to the debugger for display
      OutputDebugString(_T("Error extracting value element\r\n"));
      continue;
   }

   // Pass the name, value pair to the debugger for display
   CString strOutput = strName + _T(" equals ") + strValue + _T("\r\n");
   OutputDebugString(strOutput);
}

Requirements

Header: <afxwin.h>

See Also

Concepts

MFC Macros and Globals

Other Resources

Using CString