C++シリアル操作


#include 
#include 
#include 
#include 
/*
 * Created by HarvestWu on 2018/6/1.
 */
using namespace std;
typedef struct Str
{
    char *ch;   //                 
    int length; //   
}Str;
//   
int strAssign(Str &str,char *ch)
{
    if(str.ch)
        free(str.ch);
    int len=0;
    char *c=ch;
    while (*c)  // ch   
    {
        ++len;
        ++c;
    }
    if(len==0)
    {
        str.ch= nullptr;
        str.length=0;
        return 1;
    }
    else
    {
        str.ch=(char*)malloc(sizeof(char)*(len+1));
        if (str.ch== nullptr)
            return 0;
        else
        {
            c=ch;
            for (int i = 0; i < len; ++i,++c)
            {
                str.ch[i]=*c;
            }
            str.length=len;
            return 1;
        }
    }
}
//     
int strLength(Str str)
{
    return str.length;
}
//   
int strCompare(Str str1,Str str2)
{
    for (int i = 0; i < str1.length&& i < str2.length; ++i)
    {
        if(str1.ch[i] != str2.ch[i])
            return str1.ch[i] - str2.ch[i];
    }
    return str1.length - str2.length;
}

//   
int concat(Str &str,Str str1,Str str2)
{
    if (str.ch)
    {
        free(str.ch);
        str.ch= nullptr;
    }
    str.ch = (char*)malloc(sizeof(char)*(str1.length+str2.length+1));
    if(str.ch== nullptr)
        return 0;
    int i = 0;
    while (i < str1.length)
    {
        str.ch[i] = str1.ch[i];
        ++i;
    }
    int j = 0;
    while (j <= str1.length)
    {
        str.ch[i+j] = str2.ch[j];
        ++j;
    }
    str.length = str1.length + str2.length;
    return 1;
}
int subString(Str &subStr,Str str,int pos,int len)
{
    if (pos<0||pos>=str.length||len<0||len>str.length-pos)
        return 0;
    if(subStr.ch)
    {
        free(subStr.ch);
        subStr.ch= nullptr;
    }
    if(len==0)
    {
        subStr.ch= nullptr;
        subStr.length=0;
        return 1;
    }
    else
    {
        subStr.ch=(char*)malloc(sizeof(char)*len+1);
        int i = pos;
        int j = 0;
        while (i("this is str1");
    Str str1,str2;
    strAssign(str1,s);
    printf("str1 is:
"); display(str1); printf("the length of str1 is: %d
",strLength(str1)); s= const_cast("this is str2"); strAssign(str2,s); printf("str2 is:
"); display(str2); printf("the length of str2 is %d
",strLength(str2)); Str str; concat(str,str1,str2); printf("the concat str is:
"); display(str); Str subStr; subString(subStr,str1,1,3); printf("the subString is:
"); display(subStr); clearString(str2); printf("the length of str2 is: %d
",strLength(str2)); }