动态顺序串的基本实现

SString.h

#pragma once
#include 
#include 
#include 
#include 
#include 
#include 
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] = '#';//下标为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;//s,t不相同
}

你可能感兴趣的:(算法,数据结构)