1、串(String)(或字符串)是由零个或多个字符组成的有序序列。
2、串赋值StrAssign、串比较StrCompare、求串长StrLength、串联接Concat以及求字串SubString 5种操作构成串类型的最小操作子集,即这些操作不可能利用其他串操作来实现,反之,其他串操作(除串清除ClearString跟串销毁DestoryString外)均可在这个最小操作子集上实现。
3、利用求串长StrLength、串比较StrCompare跟求字串SubString实现搜索指定字串的C语言伪代码实现如下:
int Index(String CppLive, String T, int pos)
{
//T为非空串,若主串CppLive中第pos个字符之后存在与T相等的字串
//则返回第一个这样的字串在CppLive中的位置,否则返回0
if (pos > 0)
{
n = StrLength(CppLive); m = StrLength(T); i = pos;
while (i <= n-m+1)
{
SubString(sub, CppLive, i, m);
if (StrCompare(sub, T) != 0) ++i;
else return i; //返回字串在主串中的位置
}
}
return 0; //CppLive中不存在与T相等的子串
}
4、串的堆分配存储表示以及基本操作的C语言算法描述伪代码如下:
typedef struct {
char *ch; //若是非空字符串,则按串长分配存储空间,否则
int length; //串长度
}HString;
Status StrAssign(HString &T, char *chars)
{
//生成一个其值等于串常量chars的串T
if (T.ch) free(T.ch); //释放T原有空间
for (i = 0, c = chars; c; ++i, ++c); //求chars的长度i
if (!i) {T.ch = NULL; T.length = 0;}
else
{
if (!(T.ch = (char *)malloc(i * sizeof(char))))
exit(OVERFLOW);
T.ch[0..i-1] = chars[0..i-1];
T.length = i;
}
return OK;
}
int StrLength(HString S)
{
//返回S的元素个数,称为串的长度
return S.length;
}
int StrCompare(HString S, HString T)
{
//若S>T,则返回值>0;若S=T,则返回值=0;若S<T,则返回值<0
for (i=0; 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;
}
Status ClearString(HString &S)
{
//将S清为空串
if (S.ch) {free(S.ch); S.ch = NULL;}
S.length = 0;
return OK;
}
Status Concat(HString &T, HString S1, HString S2)
{
//用T返回由S1和S2联接而成的新串
if (T.ch) free(T.ch); //释放旧空间
if (!(T.ch = (char *)malloc(S1.length +S2.length)*sizeof(char)))
exit(OVERFLOW);
T.ch[0..S1.length-1] = S1.ch[0..S1.length-1];
T.length = S1.length +S2.length;
T.ch[S1.length..T.length-1] = S2.ch[0..S2.length-1];
return OK;
}
Status SubString(HString &SUb, HString S, int pos, int len)
{
//用Sub返回串S的第pos个字符起长度为len的字串
//其中,1<=pos<=StrLength(S)且0<=len<=StrLength(S)-pos+1
if (pos < 1 || pos > S.length || len < 0 || len > S.length -pos + 1)
return ERROR;
if (Sub.ch) free(Sub.ch); //释放旧空间
if (!len) {Sub.ch = NULL; Sub.length = 0;} //空子串
else
{
Sub.ch = (char *)malloc(len * sizeof(char));
Sub.ch[0..len-1] = S.ch[pos-1..pos+len-2];
Sub.length = len;
}
reurn OK;
}
除非注明,文章均为CppLive 编程在线原创,转载请注明出处,谢谢。



