字符串和数字的left 函数实现

来源:互联网 发布:淘宝商城软包 编辑:程序博客网 时间:2024/05/16 01:31

    //this function returns  a  pointer to  a new string  取字符串的前n位

// consisting of  the  first n characters in  the  str string,

char * left( const char * str, int n)

{

      if ( n < 0 )

           n = 0;

       char *p = new char[ n+1 ];

       int i;

      for ( i = 0; i < n && str[i] ; ++i )

          p[i] = str [ i ];

      while (i <= n )

             p [ i++] = '\0' ;

        return 0;      

}

//////////////   注意使用left 函数后用delete 来释放掉new 出来的内存。

//////********************left 函数的重载

/////  取整型数 num 的 前 ct 位数字

unsigned  long  left( unsigned  long  num,  unsigned ct )

unsigned  digitals = 1 ;

unsigned  long  n = num;

if ( ct == 0 || num == 0 )

return 0;

while( n/10 )    digitals++;

if ( digitals > ct )

 {   ct = digitals - ct ;

     while( ct - -)

         num/= 10;

        return num;

}

else   return  num;

}

原创粉丝点击