首先是串的数据结构定义,一些头文件和宏定义等
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#define MaxSize 100
#define ERROR 0
#define OK 1
using namespace std;
typedef char Str[MaxSize+1];
typedef int Status;
接下来是串的初始化:
这里的初始化我们用串的第一个字符来表示传中其余的字符的个数就是串的长度,但实际上串的长度要加1,因为我们用了第一个字符来记录串的长度。
void InitStr(Str& S) {
S[0] = 0;
return;
}
对于串赋值,把字符数组ch的字符赋值给S;
Status AssignStr(Str& S, char ch[]) {
int len = strlen(ch);
if (len > MaxSize-1) return ERROR;
else {
int i;
for (i = 1; i <= len+1; i++) {
S[i] = ch[i - 1];
}
S[0] = len;
return OK;
}
}
得到串的长度,字符的个数(实际上可以直接用S[0]来获得):
int GetLenStr(Str S) {
int ans = S[0];
return ans;
}
来判断串是否为空:
Status EmptyStr(Str S) {
if (S[0] == 0) return OK;
else return ERROR;
}
将两个串连接,即S3 = S1+S2:
Status ConcatStr(Str S1, Str S2, Str &S3) {
int i;
int len1 = GetLenStr(S1);
int len2 = GetLenStr(S2);
for (i = 1; i <= len1; i++) {
S3[i] = S1[i];
}
for (i = len1 + 1; i <= len1 + len2; i++) {
S3[i] = S2[i - len1];
}
S3[0] = i;
return OK;
}
得到串S的第pos个字/符开始长度为len的串,并赋值给Sub:
Status SubstrStr(Str S, Str& Sub, int pos, int len) {
int LenS = GetLenStr(S);
if (pos < 1 || pos + len > LenS + 1) return ERROR;
else {
int i;
for (i = pos; i <= pos + len; i++) {
Sub[i - pos + 1] = S[i];
}
Sub[0] = i-pos-1;
return OK;
}
}
把串S2插入到S1的第pos个字符之后(如果插在字符之前只需很小的变动,直接把pos变成pos-1即可):
Status Insert_Back_Str(Str& S1, Str S2, int pos) {
int LenS1 = GetLenStr(S1);
int LenS2 = GetLenStr(S2);
if (pos < 1 || pos > LenS1 + 1) return ERROR;
else {
if (LenS1 + LenS2 > MaxSize) return ERROR;
else {
for (int k = LenS1; k >= pos; k--) {
S1[k + LenS2] = S1[k];
}
int i;
for (i = 1; i <= LenS2; i++) {
S1[i + pos] = S2[i];
}
S1[0] = LenS1 + LenS2;
return OK;
}
}
}
删除串S的第pos个字符开始的长度为len的字符
Status Delete_back_Str(Str& S, int pos, int len) {
int LenS = GetLenStr(S);
if (pos < 1 || pos + len > LenS) return ERROR;
else {
int i;
for (i = pos + len; i <= LenS; i++) {
S[i - len] = S[i];
}
S[0] = LenS - len;
return OK;
}
}
来遍历一下串并输出,输出之后换行:
void PrintStr(Str S) {
int len = GetLenStr(S);
for (int i = 1; i <= len; i++) {
cout << S[i];
}
cout << endl;
}
这里是Kmp算法来进行字符的匹配:
void GetNext(Str T, int next[]) {
next[1] = 0;
int j = 1;
int k = 0;
while (j < T[0]) {
if ((k == 0) || T[j] == T[k]) {
j++;
k++;
next[j] = k;
}
else k = next[k];
}
}
int Kmp(Str S, Str T, int pos) {
int next[100];
int LenS = GetLenStr(S);
int LenT = GetLenStr(T);
GetNext(T, next);
//for (int i = 1; i <= LenT; i++) cout << next[i] << " ";
//cout << endl;
int i = 1;
int j = 1;
while (i <= LenS && j <= LenT) {
if (S[i] == T[i] || (j == 0)) {
i++;
j++;
}
else {
j = next[j];
}
}
if (j > LenT) return (i - LenT);
else return 0;
}
数据结构的串就介绍到这里。