手撕字串操作函式

uav360發表於2020-12-22

字串複製函式strcpy

#include<stdio.h>
#include<assert.h>

char* my_strcpy(char* srcString,char* desString)
{
   assert((srcString != NULL) && (desString != NULL));

   char* addr = desString;
   while((*desString++ = *srcString++) != '\0') ;

   return addr;
}

int main()
{
  char* srcString = "abcdefghijklmnopqrstuvwxyz";
  char desString[30];
  printf("desString = %s \r\n", my_strcpy(srcString, desString));
}

取字串長度strlen

#include<stdio.h>
#include<assert.h>

int my_strlen(char* String)
{
  assert(String != NULL);
  int i=0;
  while((*String++) != '\0') i++;

  return i;
}

int main()
{
  char* String = "abcdefghijklmnopqrstuvwxyz";
  printf("strlen(String) = %d \r\n", my_strlen(String));
  return 0;
}

整數轉字串itoa

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char* my_itoa(int num,char* str,int radix)
{   /*索引表*/
    char index[]="0123456789ABCDEF";
    unsigned unum;/*中間變數*/
    int i=0,j,k;
    /*確定unum的值*/
    if(radix==10&&num<0)/*十進位制負數*/
    {
        unum=(unsigned)-num;
        str[i++]='-';
    }
    else unum=(unsigned)num;/*其他情況*/
    /*轉換*/
    do{
        str[i++]=index[unum%(unsigned)radix];
        unum/=radix;
    }while(unum);
    str[i]='\0';
    /*逆序*/
    if(str[0]=='-')
        k=1;/*十進位制負數*/
    else
        k=0;
     
    for(j=k;j<=(i-1)/2;j++)
    {   char temp;
        temp=str[j];
        str[j]=str[i-1+k-j];
        str[i-1+k-j]=temp;
    }
    return str;
}

int main()
{
  char* buf = malloc(50);

  memset(buf,0,50);
  printf("255 = %s \r\n",my_itoa(255,buf,16));

  memset(buf,0,50);
  printf("0xFF = %s \r\n",my_itoa(0xFF,buf,10));

  free(buf);
  return 0;
}

字串轉整數atoi

#include<stdio.h>

long int my_atoi(const char *nptr)
{
        int c;               /* current char */
        long int total;      /* current total */
        int sign;            /* if '-', then negative, otherwise positive */

        /* skip whitespace */
        while ((*nptr == ' ') || (*nptr == '\r') || (*nptr == '\n') || ( *nptr == '\v') || (*nptr == '\f') || (*nptr == '\t')){
           ++nptr;
        }            

        c = *nptr++;
        sign = c;           /* save sign indication */

        if (c == '-' || c == '+')
            c = *nptr++;    /* skip sign */

        total = 0;

        while ((c >= '0') && (c <= '9')) {
            total = 10 * total + (c - '0');     /* accumulate digit */
            c = *nptr++;                        /* get next char */
        }

        if (sign == '-')
            return -total;
        else
            return total;   /* return result, negated if necessary */
}

int main()
{
   char buf1[] = "0123456789";
   printf("buf1 = %ld \r\n", my_atoi(buf1));

   char buf2[] = "-9876543210";
   printf("buf2 = %ld \r\n", my_atoi(buf2));

   return 0;
}

相關文章