字符串的基本操做

CMyString.h

#ifndef CMyString_h__
#define CMyString_h__

#define MAX_STRING_SIZE 1024

typedef struct cMyString_def{
    int length;
    char str[MAX_STRING_SIZE];
}CMyString;
void InitCMyString(CMyString* cs, char* s);
void Concatenate(CMyString* cs, CMyString* s);
void DeleteCS(CMyString* cs, int pos, int len);
char* GetString(CMyString* cs);
void Insert(CMyString* cs, int pos, CMyString* s);
CMyString SubString(CMyString* cs, const int pos, const int len);
#endif // CMyString_h_

CMyString.c

#include 
#include 
#include 
#include "CMyString.h"

void InitCMyString(CMyString* cs, char* s){
    char *p1, *p2;
    for (cs->length=0, p1=cs->str, p2=(char*)s; *p2 ;cs->length++){
        *(p1++) = *(p2++);
    }
    *p1 = 0;
}


void Concatenate(CMyString* cs, CMyString* s){
    if (cs->length+s->length <= MAX_STRING_SIZE){
        memcpy(cs->str+cs->length, s->str, s->length+1);
        cs->length += s->length;
    }
    else
        puts("error:string length overflow!\n");
}

void DeleteCS(CMyString* cs, int pos, int len){
    int rlen = len;
    if (pos+len >cs->length)
        rlen=cs->length - pos;
    // 这句将两种情况合在一起,,,,,,TMD
    cs->length -= rlen;
    memcpy(cs->str+pos, cs->str+pos+rlen, cs->length-pos+1);
}


char* GetString(CMyString* cs){
    char *tmpStr = (char*)malloc(sizeof(char)*(cs->length+1));
    memcpy(tmpStr, cs->str, cs->length+1);
    return tmpStr;
}

void Insert(CMyString* cs, int pos, CMyString* s){
    if (cs->length+s->length <= MAX_STRING_SIZE){
        memcpy(cs->str+pos+s->length, cs->str+pos, cs->length-pos+1);               // 先把原字符串的后和东西复制出来
        memcpy(cs->str+pos, s->str, s->length);
        cs->length += s->length;
    }
    else
        puts("error: string  length overflow.");
}

CMyString SubString(CMyString* cs, const int pos, const int len){
    int rlen = len;
    CMyString* tmpStr=(CMyString*)malloc(sizeof(CMyString));

    InitCMyString(tmpStr, " ");
    if (pos+len > cs->length)
        rlen=cs->length-pos;

    memcpy(tmpStr->str, cs->str+pos, rlen);
    tmpStr->length = rlen;
    tmpStr->str[tmpStr->length]=0;
    return *tmpStr;
}

main.c

#include "CMyString.h"
#include 
int main(){
    char str[512]="abcdefgh";
    char s[512]="xyz";
    CMyString cs, cs2;

    InitCMyString(&cs, str);
    printf("%s\n", GetString(&cs));

    DeleteCS(&cs, 2, 3);
    printf("%s\n", GetString(&cs));

    InitCMyString(&cs2, s);
    Concatenate(&cs, &cs2);
    printf("%s\n", GetString(&cs));


    printf("Debug:\n");
    printf("%s\n", cs.str);
    Insert(&cs, 0,&cs2);
    printf("%s\n\n", GetString(&cs));

    puts("取子串;");
    printf("%s\n", SubString(&cs, 2,3).str);
    return 0;
}

运行结果:
字符串的基本操做_第1张图片

转载于:https://www.cnblogs.com/laohaozi/p/8266600.html

你可能感兴趣的:(字符串的基本操做)