1. 程式人生 > >串的基本操作(C++)

串的基本操作(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;
}

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