天天看點

中英文折行儲存函數

需求:

1.可以支援中英文折行儲存

2.輸入字元串,可以對本字元串整理後傳回整理後的字元串

3.可以指定每行的英文或數字字數。

我的實作函數如下:

我的代碼實作:

int CleanUpString(char* chCleanStr, int iLineLen)
{
    //傳入字元長度
    int inputLen = strlen(chCleanStr);
    //沒有内容不清理
    if (inputLen == 0)
    {
        return -1;
    }
    //iLienLen小于等于0時
    if (iLineLen <= 0)
    {
        return -2;
    }
    //更改後的長度
    int outputLen =inputLen + inputLen/iLineLen*2+1;
    //儲存字元串暫用空間
    char* tempStr= new char[outputLen];
    //每行儲存的字元以中文的雙位元組為主
    int ilenMax = 0;
    //讀到的最後一個位置
    int tempStrPos=0;
    for (int i=0; i<strlen(chCleanStr);)
    {
        //漢字拷貝
        if (chCleanStr[i] > 127 || chCleanStr[i] < 0)
        {
            tempStr[tempStrPos] = chCleanStr[i];
            i=i+1;
            tempStrPos++;
            tempStr[tempStrPos] = chCleanStr[i];
            //下一個字處理
            i++;
            tempStrPos++;
            //每行現在字元個數
            ilenMax=ilenMax+2;
        }
        //原來字元串中有換行
        else if ('\r'==chCleanStr[i] || '\n'==chCleanStr[i])
        {
            tempStr[tempStrPos] = chCleanStr[i];
            ilenMax = 0;
            tempStrPos++;
            i++;
        }
        //數字英文拷貝
        else if (chCleanStr[i] <=127)
        {
            tempStr[tempStrPos] = chCleanStr[i];
            //下一個字處理
            i++;
            tempStrPos++;
            //每行現在字元個數
            ilenMax++;
        }
        //換行
        if (ilenMax>=iLineLen)
        {
            ilenMax = 0;
            tempStr[tempStrPos] = '\r';
            tempStrPos++;
            tempStr[tempStrPos] = '\n';
            tempStrPos++;
        }
    }
    tempStr[tempStrPos]='\0';
    //清空原有字元串
    memset(chCleanStr,0,inputLen);
    strcpy(chCleanStr,tempStr);
    delete []tempStr;
    return 0;
}
           

From:http://blog.csdn.net/dingdingko/article/details/2959510