1. 程式人生 > >字串處理函式

字串處理函式

/**
  *****************************************************************************************
  *
  * @Name	 : 浮點型轉字元
  * @Brief	 : none
  * @Input	 : str:字串指標 num:浮點數 n:精度
  * @Output	 : none
  * @Return	 : none
  *
  *****************************************************************************************
**/
int ftoa(char *str, float num, int n)        //n是轉換的精度,即是字串'.'後有幾位小數
{
    int     sumI;
    float   sumF;
    int     sign = 0;
    int     temp;
    int     count = 0;

    char *p;
    char *pp;

    if(str == NULL) return -1;
    p = str;

    /*Is less than 0*/
    if(num < 0)
    {
        sign = 1;
        num = 0 - num;
    }

    sumI = (int)num;    //sumI is the part of int
    sumF = num - sumI;  //sumF is the part of float

    /*Int ===> String*/
    do
    {
        temp = sumI % 10;
        *(str++) = temp + '0';
    }while((sumI = sumI /10) != 0);


    /*******End*******/
 

    if(sign == 1)
    {
        *(str++) = '-';
    }

    pp = str;
    
    pp--;
    while(p < pp)
    {
        *p = *p + *pp;
        *pp = *p - *pp;
        *p = *p -*pp;
        p++;
        pp--;
    }

    *(str++) = '.';     //point

    /*Float ===> String*/
    do
    {
        temp = (int)(sumF*10);
        *(str++) = temp + '0';

        if((++count) == n)
            break;
    
        sumF = sumF*10 - temp;

    }while(!(sumF > -0.000001 && sumF < 0.000001));

    *str ='\0';

    return 0;

}

/**
  *****************************************************************************************
  *
  * @Name	 : 轉置函式
  * @Brief	 : none
  * @Input	 : s:待轉換字串
  * @Output	 : none
  * @Return	 : none
  *
  *****************************************************************************************
**/
void reverse(char *s)  
{  
    char temp;  
    char *p = s;    //p指向s的頭部  
    char *q = s;    //q指向s的尾部  
    while(*q)  
        ++q;  
    q--;  
      
    //交換移動指標,直到p和q交叉  
    while(q > p)  
    {  
        temp = *p;  
        *p++ = *q;  
        *q-- = temp;  
    }   
}  


/**
  *****************************************************************************************
  *
  * @Name	 : 整型轉字元
  * @Brief	 : none
  * @Input	 : n:整型 s:字串
  * @Output	 : none
  * @Return	 : none
  *
  *****************************************************************************************
**/


void itoa(uint16_t n,char s[])
{
    uint16_t i = 0;   
    do      //從各位開始變為字元,直到最高位,最後應該反轉  
    {  
        s[i++] = n%10 + '0';  
        n = n/10;  
    }while(n > 0);  
       
    s[i] = '\0';    //最後加上字串結束符 
    
    reverse(s);
}