SString.h
#pragma once
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <iostream>
#include <stdio.h>
using namespace std;
#define SIZE 10
typedef struct String
{
char* ch;
int size;
int capacity;
}String;
void initString(String* ps);
void newCapacity(String* ps);
void printString(const String* s);
void enterData(String* ps, char* ch);
void destroyString(String* ps);
void subString(String* sub, const String* ps, int pos, int len);
int strCompare(const String* s, const String* t);
int index(const String* s, const String* t);
SString.cpp
#include "SString.h"
void initString(String* ps)
{
ps->ch = (char*)malloc(SIZE * sizeof(char) + 1);
if (NULL == ps->ch)
{
cout << strerror(errno) << endl;
exit(-1);
}
ps->ch[0] = '#';
ps->size = 0;
ps->capacity = SIZE;
}
void newCapacity(String* ps)
{
assert(ps);
int NewCapacity = ps->capacity * 2;
char* pc = (char*)realloc(ps->ch, NewCapacity * sizeof(char) + 1);
if (NULL == pc)
{
cout << strerror(errno) << endl;
exit(-1);
}
ps->ch = pc;
ps->capacity = NewCapacity;
}
void printString(const String* ps)
{
assert(ps);
if (0 == ps->size)
{
cout << "串中无数据" << endl;
return;
}
cout << "串: ";
for (int i = 1; i <= ps->size; i++)
{
cout << ps->ch[i] << " ";
}
cout << endl;
}
void enterData(String* ps, char* ch)
{
int len = strlen(ch);
if (len > ps->capacity)
{
newCapacity(ps);
}
int i = 0;
while ('\0' != ch[i])
{
ps->ch[i + 1] = ch[i];
i++;
}
ps->size = len;
}
void destroyString(String* ps)
{
assert(ps);
free(ps->ch);
ps->ch = NULL;
ps->size = ps->capacity = 0;
}
void subString(String* sub, const String* ps, int pos, int len)
{
assert(ps);
if (pos + len - 1 > ps->size)
{
cout << "子串不合法" << endl;
return;
}
for (int i = pos ; i < pos + len; i++)
{
sub->ch[i - pos + 1] = ps->ch[i];
}
sub->size = len;
}
int strCompare(const String* s, const String* t)
{
assert(s);
assert(t);
for (int i = 1; i <= s->size && i <= t->size; i++)
{
if (s->ch[i] != t->ch[i])
{
return s->ch[i] - t->ch[i];
}
}
return s->size - t->size;
}
int index(const String* s, const String* t)
{
assert(s);
assert(t);
String sub;
initString(&sub);
int i = 1;
while (i < s->size - t->size + 1)
{
subString(&sub, s, i, t->size);
if (0 == strCompare(&sub, t))
{
destroyString(&sub);
return i;
}
i++;
}
destroyString(&sub);
return 0;
}