AKever

导航

C++(2) 自定义 字符串拷贝(strcpy),整形转字符串(itoa), 2.字符串转整形(atoi)

1. 字符串拷贝(strcpy)

char* ud_strcpy(char* to, char* from)
{
    if(to == NULL || from == NULL)
        throw "invalid args!";
    while( (*to++ = *from++) != '\0' );
        return to;
}

调用:

char str = "123456"
char s[7];
ud_strcpy( s, str );

 ===================================================================

2.整形转字符串(itoa)

char* ud_itoa(int num, char* s)
{
    int j = 0, i = 0;
    char temp[20], str[20];
    
    while( num )
    {
        temp[i] = num % 10 + '0';
        i++;
        num = num / 10;
    }
    temp[i] = 0;

    i = i - 1;
    while( i>=0 )
    {
        s[j] = temp[i];
        j++;
        i--;
    }
    s[j] = 0;

    return s;
}

调用:

char pStr[20];
int  num = 1234;
printf( "pStr=%s", ud_itoa(num, pStr) );

================================================================

 3. 字符串整形(atoi)

int ud_atoi(char* str)
{
    int value = 0; //结果整数值
    int sign = 1;  //符号 '-' or '+'
    int radix = 10; //进制 '0'八进制 '0x'十六 

    //确定数值符号与进制
    if( *str == '-' ) {
        sign = -1;
        *str++;
    } else if( *str == '+' ) {
        sign = 1;
        *str++;
    }
    if( *str=='0' &&  (*(str+1)=='x' || *(str+1)=='X') ) {
        radix = 16;
        str += 2;
    } else if( *str == '0' ) {
        radix = 8;
        str ++;
    } else {
        radix = 10;
    }
    //计算
    while( *str )
    {
        if( radix == 16 )
        {
            if( *str>='0' && *str<='9' ) {
                value = (*str - '0') + value * radix;
            } else {
                value = (*str - 'a') + value * radix;
            }

        } else {
            value = (*str - '0') + value * radix;
        }
        *str ++;
    }
    return sign * value;
}

调用:

    //int ud_atoi(char* str)
    char* sNum16  = "0x1357";
    char* sNum8  = "0246";
    char* sNum10 = "3701";
    char* sNumSign = "-123";

    printf( "sNum16=%d\n", ud_atoi(sNum16) );      //sNum16=4951
    printf( "sNum8=%d\n", ud_atoi(sNum8) );        //sNum8=166
    printf( "sNum10=%d\n", ud_atoi(sNum10) );      //sNum10=3701
    printf( "sNumSign=%d\n", ud_atoi(sNumSign) );  //sNum10=3701

 

 

posted on 2014-07-13 23:56  AKever  阅读(260)  评论(0)    收藏  举报