一、基本概念
-
串(string):由0个或多个字符组成的有序序列,称为字符串,记为s=‘abcdefg’ 其中s是字符串的名字,a b c称为串的值,可以是字母、数字或者字符
-
串长度:串中元素个数
-
空串:不含任何字符的串,串长度为0
-
子串:主串中任意连续字符组成的字符串
-
串s1、s2相等的条件:
- s1、s2长度相等
- s1、s2对应位置的元素处处相等
二、串的类型
1.定长顺序串
定义:用一组地址连续的存储单元存储串值的字符序列,类似于线性表的顺序存储结构。
静态存储分布代码实现:
#define MAXLEN 30 // 用户可在255以内定义最大串长
typedef struct
{
char ch[MAXLEN];
int len;
} SString ;
动态演示:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9J6hPQ0Y-1652680719887)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/dabebec6e1d440d3b65bc37f3ba3afbb~tplv-k3u1fbpfcp-zoom-in-crop-mark:1956:0:0:0.image)]
- 其实就是依次插入
2.基本算法
串插入:
int StrInsert(SString *s, int pos, SString t)
/*在串s中下标为pos的字符之前插入串t */ { int i;
if (pos<0 || pos>s->len) /*插入位置不合法*/
return 0;
if (s->len + t.len<=MAXLEN) /*插入后串长≤MAXLEN*/
{
for (i=s->len + t.len-1;i>=t.len + pos;i--)
s->ch[i]=s->ch[i-t.len]; //将插入位置现有字符后移
for (i=0;i<t.len;i++)
s->ch[i+pos]=t.ch[i]; //在空出的位置逐个插入字符串
s->len=s->len+t.len;
}
else
{ if (pos+t.len<=MAXLEN)
/*插入后串长>MAXLEN,但串t的字符序列可以全部插入*/
{
for (i=MAXLEN-1;i>t.len+pos-1;i--)
s->ch[i]=s->ch[i-t.len]; //将插入位置现有字符后移
for (i=0;i<t.len;i++)
s->ch[i&