C string operation function implementation method summary

  • 2020-04-02 03:03:26
  • OfStack

This article illustrates the implementation of C string manipulation function. Share with you for your reference. The details are as follows:

The following is part of the C string manipulation function to achieve, perhaps in some written tests can be used!


#ifndef NULL
#define NULL ((void *)0)
#endif

void* memcpy(void *pDst, void *pSrc, int iLen)
{
  char *pTmp = (char *)pDst;
  char *pTmp2 = (char *)pSrc;
  if(0 == iLen)
    return pDst;
  while(iLen--)
    *pTmp++ = *pTmp2++;
  return pDst;
}

void* memset(void *pDst, int iSet, int iLen)
{
  char *pTmp = (char *)pDst;
  if(0 == iLen)
    return pDst;
  while(iLen--)
    *pTmp++ = (char)iSet;
  return pDst;
}

char *strcpy(char *pDst, char *pSrc)
{
  char *pRst = pDst;
  do
    *pDst++ = *pSrc;
  while(*pSrc++);
  return pRst;
}

char *strcat(char *s, char *a)
{
  char *save = s;
  for(; *s; ++s);
  while((*s++ = *a++) != 0);
  return save;
}

int strlen(char *pStr)
{
  int iLen = 0;
  while(*pStr++)
    iLen++;
  return iLen;
}

int strcmp(char *s, char *t)
{
  for(; *s == *t; s++, t++)
  {
    if(('/0' == *s) || ('/0' == *t))
    {
      if(*s == *t)
        return 0;
      else
        break;
    }
  }
  return ((*s > *t) ? 1 : -1);
}

int m_strncmp(char *s, char *t, int n)
{
  if(0 == n)
    return 0;
  for (; (--n > 0) && (*s==*t); s++,t++)
  {
    if ('/0'==*s)
      return 0;
  }
  if(*s == *t)
    return 0;
  return ((*s > *t) ? 1 : -1);
}

char* strstr(char *s, char *find)
{
  char c, sc;
  unsigned int len;
  if ((c = *find++) != 0) 
  {
    len = lzs_strlen(find);
    do 
    {
      do 
      {
        if ((sc = *s++) == 0)
          return (NULL);
      } while (sc != c);
    } while (lzs_strncmp(s, find, len) != 0);
    s--;
  }
  return ((char *)s);
}

Hope that the article described in the C programming language for you to help.


Related articles: