串的基本操作(C++)

#include"iostream"

using namespace std;

//=================串==============================
/*两个串是否相等,必须是它们串的长度以及它们各个对应位置的字符都相等时,才算是相等.
串的顺序存储结构的缺点是字符串的截断,截断就是超过预定义长度的串值被舍去.*/

//=========串的顺序存储===========
/*一般T[0]存放串的大小*/
const int MAXSIZE = 40;
struct StringType
{
	char Str[MAXSIZE];
	int length;
	struct StringType(int x) :length(0){};
};

/*输出字符串T*/
bool StringVisit(const StringType *T)
{
	if (T->length==0)
	{
		cout << "空串!" << endl;
		return false;
	}
	else
	{
		for (int i = 0; i <T->length; i++)
			cout << T->Str[i];
		cout << endl;
		return true;
	}
}

/*生成一个其值为chars的串T*/
bool StrCreate(StringType *T, char *chars)
{
	if (strlen(chars) > MAXSIZE)
		return false;
	else
	{
		T->length = strlen(chars);
		for (int i = 0; i <T->length; i++)
			T->Str[i] = chars[i];
		return true;
	}
}

/* 返回串的元素个数 */
int StrLength(StringType *T)
{
	return T->length;
}

/*串比较: 
初始条件: 串S和T存在 
操作结果: 若S>T,则返回值>0;若S=T,则返回值=0;若S < T,则返回值< 0 */
int StrComp(const StringType *T, const StringType *S)
{
	for (int i = 0; i < T->length && i < S->length; i++)
	{
		if (S->Str[i]!=T->length)
			return S->Str[i] - T->Str[i];
	}
	return S->length - T->length;

}


/* 用T返回S1和S2联接而成的新串。若未截断,则返回TRUE,否则FALSE */
bool Contact(StringType *T, StringType *S1, StringType *S2)
{
	if (S1->length + S2->length <= MAXSIZE)
	{
		for (int i = 0; i < S1->length; i++)
			T->Str[i] = S1->Str[i];
		for (int j = 0; j < S2->length; j++)
			T->Str[j] = S2->Str[j];
		T->length = S1->length + S2->length;
		return true;
	}
	else
	{
		for (int i = 0; i < S1->length; i++)
			T->Str[i] = S1->Str[i];
		for (int j = 0; j < MAXSIZE-S1->length; j++)
			T->Str[j] = S2->Str[j];
		T->length = MAXSIZE;
		return false;
	}
}

/* 用Sub返回串S的第pos个字符起长度为len的子串。 */
bool SubString(StringType *T, StringType *Sub, int pos, int len)
{
	if (T->length < 0 || pos < 0 || len<0 || pos>T->length || len>T->length - pos)
		return false;
	else
	{
		Sub->length = len;
		for (int i = 0; i < len; i++)
			Sub->Str[i] = T->Str[pos + i];
		return true;
	}
}


//kmp模式匹配算法



int main()
{
	char *cc = "asdfchjksj";
	StringType *T = new StringType(0);
	StrCreate(T, cc);
	return 0;
}


更新中.........

猜你喜欢

转载自blog.csdn.net/cat1992/article/details/75675136