定长顺序串的基本操作

定长顺序串采用的是数组方法进行存储,空间分配一次完成,可以实行如下的基本操作

#include 
#include 
using namespace std;
#define MAXSTRLEN 200
#define TRUE 1
#define FALSE 0
#define  OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef unsigned char sstring[MAXSTRLEN + 1];
int strassig(sstring &T, char chars[])//赋值操作 
{
	int i;
	if (strlen(chars)>MAXSTRLEN)
		return ERROR;
	else
	{
		T[0] = strlen(chars);
		for (i = 0; iMAXSTRLEN)
		return ERROR;
	else
	{
		for (int i = 0; i <= s[0]; i++)
			T[i] = s[i];
	}
	return OK;
}

int strempty(sstring s)//判空操作 
{
	if (s[0] == 0)
		return OK;
	else
		return ERROR;
}

int strcompare(sstring s, sstring T)//比大小 
{
	int i;
	for (i = 1; i <= s[0] && i <= T[0]; i++)
	if (s[i] != T[i])
		return (s[i] - T[i]);
	return (s[i] - T[i]);
}

int strlength(sstring s)//串长 
{
	return s[0];
}

void clearstring(sstring &s)//清空字符串 
{
	s[0] = 0;
	s[1] = '\0';
}

void concat(sstring &T, sstring s1, sstring s2)// 连接两个字符串 
{
	int i, j, uncut;
	if (s1[0] + s2[0] <= MAXSTRLEN)
	{
		for (i = 1; is[0] || len<0 || len>s[0] - pos + 1)
		return ERROR;
	for (int i = 1; i <= len; i++)
		sub[i] = s[pos - 1 + i];
	sub[0] = len;
	return OK;
}

int strinsert(sstring &s, int pos, sstring T)//插入 
{
	int i;
	if (s[0] + T[0] <= MAXSTRLEN)
	{
		for (i = s[0]; i >= pos; i--)
			s[i + T[0]] = s[i];
		for (i = pos; i= len)
	{
				for (int i = pos; i <=s[0]-len; i++)
		{
			s[i] = s[i + len];
		}
			s[0] = s[0] - len;
	}
	else if (s[0] - pos < len)
	{
		s[pos] = '\0';
		s[0] = pos - 1;
	}
}

void shuchu(sstring s)
{
	for (int i = 1; i <= s[0]; i++)
		cout << s[i];
	cout << endl;
}
int main()
{
	int i, m, n;
	sstring T, s, sub;
	char chars1[11] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
	char chars2[11] = { 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't' };
	strassig(T, chars1);
	cout << "将chars1的值赋予T:";
	shuchu(T);
	cout << "字符串的长度为:" << strlength(T) << endl;
	cout << "将chars2的值赋予s:";
	strassig(s, chars2);
	shuchu(s);
	cout << "判断T与s的大小:";
	if (strcompare(s, T) == 0)
		cout << 's' << '=' << 'T' << endl;
	else if (strcompare(s, T) < 0)
		cout << 's' << '<' << 'T' << endl;
	else if (strcompare(s, T) > 0)
		cout << 's' << '>' << 'T' << endl;
	cout << "将字符串T和s连接起来:";
	concat(T, T, s);
	shuchu(T);
	cout << "将s的值赋予T:";
	strcopy(T, s);
	shuchu(T);
	cout << "判断字符串T是否为空:";
	if (strempty(T) == 1)
		cout << "字符串为空" << endl;
	else if (strempty(T) == 0)
		cout << "字符串不为空" << endl;
	cout << "请输入m,n,并求字符串T中第m个字符以后长度为n的字符子串:" << endl;
	cin >> m;
	cin >> n;
	cout << "字符子串为:";
	substring(sub, T, m, n);
	shuchu(sub);
	cout << "输入m" << endl;
	cin >> m;
	cout << "将chars1的值赋予s,并在串s的第m个字符之前插入串T" << endl;
	strassig(s, chars1);
	strinsert(s, m, T);
	cout << "输出新串:";
	shuchu(s);
	cout << "请输入m,n,并删除字符串s中第m个元素以后长度为n的子串" << endl;
	cin >> m;
	cin >> n;
	cout << "输出新串:";
	strdelete(s, m, n);
	shuchu(s);
	system("pause");
	return 0;
}


你可能感兴趣的:(定长顺序串)