串的基本操作
#include<iostream>
using namespace std;
#define MAXLEN 255
typedef struct{
char ch[MAXLEN];
int length;
} SString;
// 求子串操作,串的第一元素是从索引下标1开始的
bool SubString(SString &Sub,SString S,int pos,int len){
// 判断子串的范围是否越界,越界就做不了了呀
if (pos+len-1 > S.length){
return false;
}
for (int i = pos; i < pos + len;i++){
Sub.ch[i - pos + 1] = S.ch[i];
}
Sub.length = len;
return true;
}
// 串的比较操作。若S>T,则返回值>0;若S=T,则返回值=0;若S<T,则返回值<0;
int StrCompare(SString S,SString T){
for (int i = 1; i < S.length && i < T.length;i++){
if (S.ch[i]!=T.ch[i])
{
return S.ch[i] - T.ch[i];
}
// 若扫描的所有字符都相同,则长度长的串更大
return S.length - T.length;
}
}
// 定位操作。若主串S中存在与串T值相同的子串,则返回它在主串S中第一次出现的位置;否则函数值为0。
// S是主串,T是待匹配子串
int Index(SString S,SString T){
int i = 1, n = S.length, m = T.length;
SString sub; // 用于暂存子串
while (i<=n-m+1)
{
SubString(sub, S, i, m);
if (StrCompare(sub,T)!=0)
{
++i;
}
else {
return i; // 找到啦,并返回子串在主串中的位置
}
}
return 0; // S中不存在与T相等的子串
}
串的存储结构
#include<iostream>
using namespace std;
// 串的顺序存储-静态数组实现
#define MAXLEN 255 // 预定义最大串长为255
typedef struct{
char ch[MAXLEN]; // 每个分量存储一个字符
int length; // 串的实际长度
} SString;
// 串的顺序存储-动态数组实现-堆分配存储-使用完需要手动free
typedef struct {
char *ch; // 按串长分配存储区,ch指向串的基地址
int length;
} HString;
HString S;
S.ch = (char *) malloc(MAXLEN * sizeof(char));
S.length = 0;
// 串的链式存储
typedef struct StringNode{
char ch; // 每一个节点只能存储一个字符,存储密度低
struct StringNode *next;
} StringNode, *String;
typedef struct StringNode{
char ch[99]; //提高存储密度
struct StringNode *next;
} StringNode, *String;