串的基本数据类型
定长顺序存储
初始化赋值
bool StrAssign(SString T, char *chars)
{
int i;
if (strlen(chars) > MAXSIZE)
{
for (i = 1; i <= MAXSIZE; ++i)
T[i] = *(chars + i - 1);
T[0] = MAXSIZE;
}
else
{
T[0] = strlen(chars); //p.s.此时T[0]存入的是int类型的数据,打印%s时无法显示
for (i = 1; i <= T[0]; ++i)
T[i] = *(chars + i - 1);
return OK;
}
}
//
int StrLength(SString s) {
return s[0]+1;
}
bool StrCopy(SString T, SString s) {
int slen = StrLength(s);
if (!slen) {
return ERROR;
}
for (int i = 1; i < slen; i++) {
T[i] = s[i];
}
T[0] = slen;
return OK;
}
void StrPrint(SString T) {
int len = StrLength(T);
for (int i = 1; i < len; i++) {
cout << T[i]<<" ";
}
cout << endl;
}
bool StrCat(SString T, SString s) {
int tLenght = StrLength(T);
int sLength = StrLength(s);
if (tLenght + sLength >= MAXSIZE) {
return ERROR;
}
int j = 1;
for (int i = tLenght; i < tLenght + sLength; i++) {
T[i] = s[j];
j++;
if (j > sLength) {
break;
}
}
T[0] = tLenght + sLength;
return OK;
}
堆分配存储
参考 https://blog.csdn.net/ta893115871/article/details/8119040
typedef struct {
char *ch;
int len;
} HString;
bool InitHString(HString* s) {
s->ch = (char*)malloc(sizeof(char));
if (NULL == s->ch)
return ERROR;
s->ch = NULL;
s->len = 0;
return OK;
}
bool StrAssign(HString *T, const char *s) {
if (T->ch)
free(T->ch);
int length = 0, i;
while (s[length] != '\0')
length++;
T->ch = (char*)malloc(length * sizeof(char));
if (!T->ch)
return ERROR;
for (i = 0; i < length; i++)
*(T->ch + i) = *(s + i);
T->len = length;
*(T->ch + T->len) = '\0';
return OK;
}
朴素的模式匹配算法
int Index(SString T, SString S, int pos) {
int i = pos;
int j = 1;
while (i <= S[0] && j <= T[0]) {
if (S[i] == T[i]) {
i++;
j++;
}
else {
i = i - j + 2; //退回到上次匹配的下一位
j = 1;
}
}
if (j > T[0]) {
return i - T[0];
}
else
return 0;
}
KMP模式匹配算法
参考 https://www.cnblogs.com/dusf/p/kmp.html
https://blog.csdn.net/x__1998/article/details/79951598
int KMP(char * t, char * p)
{
int i = 0;
int j = 0;
while (i < strlen(t) && j < strlen(p))
{
if (j == -1 || t[i] == p[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j == strlen(p))
return i - j;
else
return -1;
}
void getNext(char * p, int * next)
{
next[0] = -1;
int i = 0, j = -1;
while (i < strlen(p))
{
if (j == -1 || p[i] == p[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}