Wednesday, 8 April 2015

Frequently used String operations in C & C++

Frequently used String operations in C & Cpp with code examples:

So, the below are the some of the working and perfectly tested common string operations, that we have used in our projects.

GetStrLength
Strdup
AddString2List
GetCount
Destroy
StrTokenizeCmplx
Strcpy
StrEqual
FindStrEqualn
MakeStrLower


#ifndef _COMMON_STR_FUNCS_H_

#define _ COMMON_STR_FUNCS_H_

#include <assert.h>

    /* This function is used to find the length of the string */

  Unsigned short GetStrLength (const char* pszStr);

    /* This function is used to duplicate the input string to the output string */

  char* Strdup (const char*  pszIn);

    /* This function is used to add the input string to the string list */

  void AddString2List (char**& ppszStrList,

                       const char* pcchrNewString);

   /* This function is used to get the count of the string list */

  Unsigned short GetCount (char **ppszStrLst);


    /* This function is used to destroy the

       heap memory allocated for the string list */

  void Destroy (char**& ppszLst);

    /* This function is used to tokenize the string as per the delimites */

  char** StrTokenizeCmplx (const char*  pszString,

                           const char*  pszDelimiters,

                           _BOOL bHonourStrings = _FALSE,

                           _BOOL bAllowEmptyTokens = _FALSE

                          );

    /* This function is used to copy the input string to the output string */

  void Strcpy (char* pszOut, const char* pszIn);



    /* This function is used to verify the two input string are equal or not */

  _BOOL StrEqual (const char* pszStr1, const char*  pszStr2);

    /* This function is used to verify the given

       part of two strings are equal or not */

  _BOOL FindStrEqualn(const char* pszStr1, const char* pszStr2, size_t nLen);


    /* This function is used to convert the given string to the lower case */

  char* MakeStrLower (const char *pcchrStr);

#endif _COMMON_STR_FUNCS_H_
 
The implementation of the each function in the above header file is shown below
#include "stdafx.h"

#include "StrFuns.h"

#include <string>


Function that is used to find the string length
Unsigned short GetStrLength (const char* pcchrStr /* input string */)

{
  unsigned short usLen = 0;  /* length of the string to be measured */
  if (pcchrStr != NULL) {

    while (pcchrStr [usLen] != '\0')

   { usLen++; }  /* Increment counter. */

  }
  return usLen;  /* Return string length */

}


Function that is used to duplicate the string from destination to the source
char* Strdup (const char*  pcchrStr  /* string, to be duplicated */)

{
  char* pszOut = NULL;

  Unsigned short usLen = 0;  /* input string length */
  usLen = GetStrLength (pcchrStr);  /* Get length of the input string */

  pszOut = (char*)malloc (usLen + 1); /* Allocate memory. */

  /* Copy input string */

  memcpy (pszOut, pcchrStr, usLen + 1);

  return pszOut;  /* Return duplicated string. */

}


This function is used to get the count of the string list
;u

unsigned short GetCount (char **ppszStrLst  /* Recieve string list */)

{

  unsigned short usCnt = 0;  // Initialize count.

  if (ppszStrLst != NULL) {

    while (*ppszStrLst != NULL)

   { usCnt++; ppszStrLst++; }  /* increment the counter */

  }

  /* return the count */

  return usCnt;

}

void AddString2List (char**& ppszStrLst,  // string list
                     const char* pcchrNewString  // new string to be appended

                    )

{

  unsigned short usCnt = 0;  /* counter to identify the

                        no of elements in the list */

  /* New string is NULL. Do not append */

  if (pcchrNewString == NULL)

    { return;}

  /* Expand string list to accomodate for new string */

  if (ppszStrLst == NULL)

    { ppszStrLst = (char**)malloc (sizeof (char*) * 2); }

  else {

        /* Count the number of strings */

    usCnt = GetCount (ppszStrLst); 

    ppszStrLst = (char**)realloc (ppszStrLst,

                                      sizeof (char*) * (usCnt + 2));
  }

  /* append the new string */

  ppszStrLst [usCnt] = Strdup (pcchrNewString);

  ppszStrLst [usCnt + 1] = NULL;

}

This function is used to destroy the heap memory allocated for the string list
void Destroy (char**& ppszStrLst  /* string list, to be freed */)

{
  char **ppszPtr;
  if (ppszStrLst != NULL) {
    ppszPtr = ppszStrLst;

    /* iterate through each item and free memory */

    while (*ppszPtr != NULL)

      { free (*ppszPtr); ppszPtr++; }

    /* free the list and set to NULL */

    free (ppszStrLst); ppszStrLst = NULL;

  }

}


This function is used to convert the given string to the lower case
char* MakeStrLower (Const char *pcchrStr)

{
  /* output string */

  char  *pszOut = NULL;

  /* ensure that the input string should not be NULL */

  assert (pcchrStr != NULL);

  unsigned short usLen = GetStrLength (pcchrStr), /* length of input string */

         usInd = 0; /* iterator */

  /* allocate enough memory to store string in lower case */

  pszOut = (char*)calloc ((usLen+1), sizeof(char));



  /* iterate through each character in the string and

     convert to lower case, if required. Save character

     in the output string. */

  while (*pcchrStr != '\0') {

    pszOut[usInd] = (*pcchrStr >= 65 && *pcchrStr <= 90) ?

                    (*pcchrStr) + 32 : *pcchrStr;

    pcchrStr++; usInd++;

  }

  return pszOut;

}


This function is used to tokenize the string as per the delimites
char** StrTokenizeCmplx (const char*  pcchrStr, const char*  pcchrDelim,

                        _BOOL bHonourStrings, _BOOL bAllowEmptyTokens

                        )

{



  char **ppszRetList = NULL,  /* output string list */

        *pszToken = NULL;  /* temporary token */



  int    nTokenMax, /* maximum length of the token */

         nTokenLen; /* token length */

  _BOOL bInString = false; /* instring indicator */

  /* allocate the memory for the active token */

  nTokenMax = 10;

  pszToken = (char *) calloc (nTokenMax, 1);   

  /* iterate through each character and append to active token */

  while (pcchrStr != NULL && *pcchrStr != '\0') {

    /* reset the token length */

    bInString = false; nTokenLen = 0;

    for (; *pcchrStr != '\0'; pcchrStr++) {

      if (!bInString && strchr (pcchrDelim, *pcchrStr) != NULL) {

        /* delimiter found. break from the loop and

           append to the list  */

        pcchrStr++; break;

      }



      if (bHonourStrings && *pcchrStr == '"') {

        /* double quote (begining or ending) found. update

           instring and continue */

        bInString = bInString ? false : true;

        continue;

      }

      /* if the character is a special character

         increment the counter */

      if (bInString && pcchrStr[0] == '\\' && pcchrStr[1] == '"')

        { pcchrStr++; }

      else if (bInString && pcchrStr[0] == '\\' && pcchrStr[1] == '\\')

        { pcchrStr++; }



      if (nTokenLen >= nTokenMax - 1) {

        /* allocate more memory for the token */

        nTokenMax = nTokenMax * 2 + 10;

        pszToken = (char *)realloc (pszToken, nTokenMax);

      }

      /* save the character in the token */

      pszToken[nTokenLen] = *pcchrStr; nTokenLen++;

    }

    /* set last character of the token to '\0' */

     pszToken[nTokenLen] = '\0';

    /* Append to list if empty tokens allowed */

    if (pszToken[0] != '\0' || bAllowEmptyTokens)

      { AddString2List (ppszRetList, pszToken); }



    if  (*pcchrStr == '\0' && bAllowEmptyTokens &&

         strchr(pcchrDelim, *(pcchrStr-1)))

      { AddString2List (ppszRetList, ""); }

  }

  /* free token string and set to NULL */

  free (pszToken); pszToken = NULL;

  return ppszRetList;

}

This function is used to verify the two input string are equal or not
_BOOL StrEqual (const char* pcchrStr1,  /* input string 1 */

             const char* pcchrStr2   /* input string 2 */

            )

{

  /* both the strings are null. return true */

  if (pcchrStr1 == NULL && pcchrStr2 == NULL)

    { return true; }

  /* one of the string is null. return false */

  if (pcchrStr1 == NULL || pcchrStr2 == NULL)

    { return false; }

  if (*pcchrStr1 != *pcchrStr2)

    { return false; } /* first byte is not equal. return false */

  /* compare the two strings */

  if (!strcmp(pcchrStr1, pcchrStr2))

    { return true; }

  return false;

}


This function is used to verify the given part of two strings are equal or not
_BOOL FindStrEqualn(const char* pcchrStr1, const char*  pcchrStr2, size_t tLen)

{



  _BOOL bRCode = false;



  if (pcchrStr1 == NULL && pcchrStr2 == NULL)

    { bRCode = true; } /* both the strings are null. return true */



  else if (pcchrStr1 == NULL || pcchrStr2 == NULL)

    { bRCode = false; } /* one of the string is null. return false */



  else if (*pcchrStr1 != *pcchrStr2)

    { bRCode = false; } /* first byte is not equal. return false */



  else if (!strncmp (pcchrStr1, pcchrStr2, tLen))

    { bRCode = true; }



  return bRCode;

}


No comments: