String library.

Dependents:   CheckSum RN41 RealTimeClock TVZ_MU_Seminar ... more

StrLib.cpp

Committer:
AkinoriHashimoto
Date:
2015-09-02
Revision:
2:14f3ff21096e
Parent:
1:7c89cd414311
Child:
4:17e03f0747d9

File content as of revision 2:14f3ff21096e:

#include "StrLib.h"

long A2I(string str, int base)   // Error; rtn '-1'
{
    long ans= 0, tmp= 0;
    int leng= str.size();   // String Length;
    char chr[1];
    for(int i=0; i<leng; i++) {
        // string -> char
        strcpy(chr, str.substr((leng-1)-i, 1).c_str());

        if('0'<=chr[0] && '9'>=chr[0])
            tmp= chr[0]-'0';
        else if('A'<=chr[0] && 'F'>=chr[0])
            tmp= chr[0]-'A'+0x0A;   // ex. C=12= 2(C-A)+ 10(0x0A)
        else if('a'<=chr[0] && 'f'>=chr[0])
            tmp= chr[0]-'a'+0x0A;
        else
            return -1;
//        UART_BT.printf("%s;%d\n", chr[0], tmp);
        ans+= tmp* (int)pow((double)base,(double)i);
//        UART_BT.printf("ans%d\n", ans);
    }
    return ans;
}
string I2A(int num, int base, int digitNum)
{
    char tmpChr[33];
    string format= "%";

    // Digit Num.
    if(digitNum > 0) {  // 0以外
        char tmp[1];
        tmp[0]= '0'+ digitNum;
        format += tmp[0];
        format += ".";
        format += tmp[0];   // +でつなげると、charの和(オーバーフロー)起こす。
    }

    if(base== 8)
        format += "o";
    if(base==10)
        format += "d";
    if(base==16)
        format += "x";
//    log_BTSD(format);

    sprintf(tmpChr, format.c_str(), num);
    string tmpStr= tmpChr;
    return tmpStr;
}

string F2A(float num, int fieldWidth, int decimalPlaces)
{
    if(!(0<=fieldWidth && fieldWidth<30))
        return "ERR; fieldWidth.";
    if(!(0<=decimalPlaces && decimalPlaces<30) )
        return "ERR; decimalPlaces.";
    if(fieldWidth < decimalPlaces+2)
        return "ERR; fieldWidth < decimalPlaces+2";

    char tmpChr[33];
    string format= "%"+ I2A(fieldWidth)+ "."+ I2A(decimalPlaces)+ "f";
    sprintf(tmpChr, format.c_str(), num);
    string tmpStr= tmpChr;
    return tmpStr;
}
string F2A(float num)
{
    char tmpChr[33];
    sprintf(tmpChr, "%f", num);
    string tmpStr= tmpChr;
    return tmpStr;
}

bool strCompare(string trg, string cmp, int idx)
{
    int id= trg.find(cmp, idx);
    if(id == string::npos)
        return false;
    return id == idx;
}

string toAlpanumeric(string str, bool toLarge)
{
    string ans= "";
    bool num, small, large;
    for (int i= 0; i < str.size(); i++) {
        num= small= large= false;
        if('0' <= str[i] && str[i] <= '9')
            num= true;
        else if('A' <= str[i] && str[i] <= 'Z')
            large= true;
        else if('a' <= str[i] && str[i] <= 'z')
            small= true;

        if(toLarge && small)
            str[i] -= 0x20;  // small -> large
        if(num || large || small)
            ans += str[i];
    }

    return ans;
}