zoukankan      html  css  js  c++  java
  • 数据结构(十五)串的顺序存储结构(顺序串)

      一、串的定义:串(String)是由零个或多个字符组成的有限序列,又名叫字符串。

      二、串中的字符数目n称为串的长度,零个字符的串称为空串(null string),它的长度为零。子串在主串中的位置就是子串的第一个字符在主串中的序号。

      三、串的大小:首先比较每个字符对应的ASCII码,然后比较长度n。

      四、串中关注更多的是查找子串位置、得到指定位置子串、替换子串等操作。

      五、串的顺序存储结构是用一组地址连续的存储单元来存储串中的字符序列的。按照预定义的大小,为每个定义的串变量分配一个固定长度的存储区。一般是用定长数组来定义。

      六、串的链式存储结构,与线性表是相似的,但由于串结构的特殊性,结构中的每个元素数据是一个字符,如果也简单的应用链表存储串值,一个结点对应一个字符,就会存在很大的空间浪费。因此,可以考虑一个结点存放多个字符,但是串的链式存储结构除了在连接串与串操作时有一定方便之外,总的来说不如顺序存储灵活,性能也不如顺序存储结构好。

      七、串的顺序存储结构的C语言代码实现:

    #include "string.h"
    #include "stdio.h"    
    #include "stdlib.h"   
    #include "io.h"  
    #include "math.h"  
    #include "time.h"
    
    #define OK 1
    #define ERROR 0
    #define TRUE 1
    #define FALSE 0
    
    #define MAXSIZE 40 /* 存储空间初始分配量 */
    
    typedef int Status;        /* Status是函数的类型,其值是函数结果状态代码,如OK等 */
    typedef int ElemType;    /* ElemType类型根据实际情况而定,这里假设为int */
    
    typedef char String[MAXSIZE+1]; /*  0号单元存放串的长度 */
    
    /* 生成一个其值等于chars的串T */
    Status StrAssign(String T,char *chars)
    { 
        int i;
        if(strlen(chars)>MAXSIZE)
            return ERROR;
        else
        {
            T[0]=strlen(chars);
            for(i=1;i<=T[0];i++)
                T[i]=*(chars+i-1);
            return OK;
        }
    }
    
    /* 由串S复制得串T */
    Status StrCopy(String T,String S)
    { 
        int i;
        for(i=0;i<=S[0];i++)
            T[i]=S[i];
        return OK;
    }
    
    /* 若S为空串,则返回TRUE,否则返回FALSE */
    Status StrEmpty(String S)
    { 
        if(S[0]==0)
            return TRUE;
        else
            return FALSE;
    }
    
    /*  初始条件: 串S和T存在 */
    /*  操作结果: 若S>T,则返回值>0;若S=T,则返回值=0;若S<T,则返回值<0 */
    int StrCompare(String S,String T)
    { 
        int i;
        for(i=1;i<=S[0]&&i<=T[0];++i)
            if(S[i]!=T[i])
                return S[i]-T[i];
        return S[0]-T[0];
    }
    
    /* 返回串的元素个数 */
    int StrLength(String S)
    { 
        return S[0];
    }
    
    /* 初始条件:串S存在。操作结果:将S清为空串 */
    Status ClearString(String S)
    { 
        S[0]=0;/*  令串长为零 */
        return OK;
    }
    
    /* 用T返回S1和S2联接而成的新串。若未截断,则返回TRUE,否则FALSE */
    Status Concat(String T,String S1,String S2)
    {
        int i;
        if(S1[0]+S2[0]<=MAXSIZE)
        { /*  未截断 */
            for(i=1;i<=S1[0];i++)
                T[i]=S1[i];
            for(i=1;i<=S2[0];i++)
                T[S1[0]+i]=S2[i];
            T[0]=S1[0]+S2[0];
            return TRUE;
        }
        else
        { /*  截断S2 */
            for(i=1;i<=S1[0];i++)
                T[i]=S1[i];
            for(i=1;i<=MAXSIZE-S1[0];i++)
                T[S1[0]+i]=S2[i];
            T[0]=MAXSIZE;
            return FALSE;
        }
    }
    
    /* 用Sub返回串S的第pos个字符起长度为len的子串。 */
    Status SubString(String Sub,String S,int pos,int len)
    {
        int i;
        if(pos<1||pos>S[0]||len<0||len>S[0]-pos+1)
            return ERROR;
        for(i=1;i<=len;i++)
            Sub[i]=S[pos+i-1];
        Sub[0]=len;
        return OK;
    }
    
    /* 返回子串T在主串S中第pos个字符之后的位置。若不存在,则函数返回值为0。 */
    /* 其中,T非空,1≤pos≤StrLength(S)。 */
    int Index(String S, String T, int pos) 
    {
        int i = pos;    /* i用于主串S中当前位置下标值,若pos不为1,则从pos位置开始匹配 */
        int j = 1;                /* j用于子串T中当前位置下标值 */
        while (i <= S[0] && j <= T[0]) /* 若i小于S的长度并且j小于T的长度时,循环继续 */
        {
            if (S[i] == T[j])     /* 两字母相等则继续 */
              {
                ++i;
                 ++j; 
              } 
              else                 /* 指针后退重新开始匹配 */
              {  
                 i = i-j+2;        /* i退回到上次匹配首位的下一位 */
                 j = 1;             /* j退回到子串T的首位 */
              }      
        }
        if (j > T[0]) 
            return i-T[0];
        else 
            return 0;
    }
    
    
    /*  T为非空串。若主串S中第pos个字符之后存在与T相等的子串, */
    /*  则返回第一个这样的子串在S中的位置,否则返回0 */
    int Index2(String S, String T, int pos) 
    {
        int n,m,i;
        String sub;
        if (pos > 0) 
        {
            n = StrLength(S);    /* 得到主串S的长度 */
            m = StrLength(T);    /* 得到子串T的长度 */
            i = pos;
            while (i <= n-m+1) 
            {
                SubString (sub, S, i, m);    /* 取主串中第i个位置长度与T相等的子串给sub */
                if (StrCompare(sub,T) != 0)    /* 如果两串不相等 */
                    ++i;
                else                 /* 如果两串相等 */
                    return i;        /* 则返回i值 */
            }
        }
        return 0;    /* 若无子串与T相等,返回0 */
    }
    
    
    /*  初始条件: 串S和T存在,1≤pos≤StrLength(S)+1 */
    /*  操作结果: 在串S的第pos个字符之前插入串T。完全插入返回TRUE,部分插入返回FALSE */
    Status StrInsert(String S,int pos,String T)
    { 
        int i;
        if(pos<1||pos>S[0]+1)
            return ERROR;
        if(S[0]+T[0]<=MAXSIZE)
        { /*  完全插入 */
            for(i=S[0];i>=pos;i--)
                S[i+T[0]]=S[i];
            for(i=pos;i<pos+T[0];i++)
                S[i]=T[i-pos+1];
            S[0]=S[0]+T[0];
            return TRUE;
        }
        else
        { /*  部分插入 */
            for(i=MAXSIZE;i<=pos;i--)
                S[i]=S[i-T[0]];
            for(i=pos;i<pos+T[0];i++)
                S[i]=T[i-pos+1];
            S[0]=MAXSIZE;
            return FALSE;
        }
    }
    
    /*  初始条件: 串S存在,1≤pos≤StrLength(S)-len+1 */
    /*  操作结果: 从串S中删除第pos个字符起长度为len的子串 */
    Status StrDelete(String S,int pos,int len)
    { 
        int i;
        if(pos<1||pos>S[0]-len+1||len<0)
            return ERROR;
        for(i=pos+len;i<=S[0];i++)
            S[i-len]=S[i];
        S[0]-=len;
        return OK;
    }
    
    /*  初始条件: 串S,T和V存在,T是非空串(此函数与串的存储结构无关) */
    /*  操作结果: 用V替换主串S中出现的所有与T相等的不重叠的子串 */
    Status Replace(String S,String T,String V)
    { 
        int i=1; /*  从串S的第一个字符起查找串T */
        if(StrEmpty(T)) /*  T是空串 */
            return ERROR;
        do
        {
            i=Index(S,T,i); /*  结果i为从上一个i之后找到的子串T的位置 */
            if(i) /*  串S中存在串T */
            {
                StrDelete(S,i,StrLength(T)); /*  删除该串T */
                StrInsert(S,i,V); /*  在原串T的位置插入串V */
                i+=StrLength(V); /*  在插入的串V后面继续查找串T */
            }
        }while(i);
        return OK;
    }
    
    /*  输出字符串T */
    void StrPrint(String T)
    { 
        int i;
        for(i=1;i<=T[0];i++)
            printf("%c",T[i]);
        printf("
    ");
    }
    
    
    int main()
    {
        
        int i,j;
        Status k;
        char s;
        String t,s1,s2;
        printf("请输入串s1: ");
        
        k=StrAssign(s1,"abcd");
        if(!k)
        {
            printf("串长超过MAXSIZE(=%d)
    ",MAXSIZE);
            exit(0);
        }
        printf("串长为%d 串空否?%d(1:是 0:否)
    ",StrLength(s1),StrEmpty(s1));
        StrCopy(s2,s1);
        printf("拷贝s1生成的串为: ");
        StrPrint(s2);
        printf("请输入串s2: ");
        
        k=StrAssign(s2,"efghijk");
        if(!k)
        {
            printf("串长超过MAXSIZE(%d)
    ",MAXSIZE);
            exit(0);
        }
        i=StrCompare(s1,s2);
        if(i<0)
            s='<';
        else if(i==0)
            s='=';
        else
            s='>';
        printf("串s1%c串s2
    ",s);
        k=Concat(t,s1,s2);
        printf("串s1联接串s2得到的串t为: ");
        StrPrint(t);
        if(k==FALSE)
            printf("串t有截断
    ");
        ClearString(s1);
        printf("清为空串后,串s1为: ");
        StrPrint(s1);
        printf("串长为%d 串空否?%d(1:是 0:否)
    ",StrLength(s1),StrEmpty(s1));
        printf("求串t的子串,请输入子串的起始位置,子串长度: ");
    
        i=2;
        j=3;
        printf("%d,%d 
    ",i,j);
    
        k=SubString(s2,t,i,j);
        if(k)
        {
            printf("子串s2为: ");
            StrPrint(s2);
        }
        printf("从串t的第pos个字符起,删除len个字符,请输入pos,len: ");
        
        i=4;
        j=2;
        printf("%d,%d 
    ",i,j);
    
    
        StrDelete(t,i,j);
        printf("删除后的串t为: ");
        StrPrint(t);
        i=StrLength(s2)/2;
        StrInsert(s2,i,t);
        printf("在串s2的第%d个字符之前插入串t后,串s2为:
    ",i);
        StrPrint(s2);
        i=Index(s2,t,1);
        printf("s2的第%d个字母起和t第一次匹配
    ",i);
        SubString(t,s2,1,1);
        printf("串t为:");
        StrPrint(t);
        Concat(s1,t,t);
        printf("串s1为:");
        StrPrint(s1);
        Replace(s2,t,s1);
        printf("用串s1取代串s2中和串t相同的不重叠的串后,串s2为: ");
        StrPrint(s2);
    
    
        return 0;
    }
    
    
    
    输出为:
    请输入串s1: 串长为4 串空否?0(1:是 0:否)
    拷贝s1生成的串为: abcd
    请输入串s2: 串s1<串s2
    串s1联接串s2得到的串t为: abcdefghijk
    清为空串后,串s1为: 
    串长为0 串空否?1(1:是 0:否)
    求串t的子串,请输入子串的起始位置,子串长度: 2,3 
    子串s2为: bcd
    从串t的第pos个字符起,删除len个字符,请输入pos,len: 4,2 
    删除后的串t为: abcfghijk
    在串s2的第1个字符之前插入串t后,串s2为:
    abcfghijkbcd
    s2的第1个字母起和t第一次匹配
    串t为:a
    串s1为:aa
    用串s1取代串s2中和串t相同的不重叠的串后,串s2为: aabcfghijkbcd

      八、串的顺序存储结构的Java语言代码实现(和C语言代码有出入):

    • 接口类:
    package bigjun.iplab.sequenceString;
    
    public interface SeqStrINF {
        // 判断顺序串是否为空
        public boolean isstrEmpty();
        // 将一个已经存在的顺序串置成空表
        public void strClear();
        // 求顺序串的长度
        public int strLength();
        // 读取并返回串中的第index个字符值
        public char charAt(int index) throws Exception;
        // 返回当前串中从序号begin开始,到序号end-1为止的子串
        public SeqStrINF strSubstr(int begin, int end) throws Exception;
        // 在当前串的第offset个字符之前插入串str
        public SeqStrINF strInsert(int offset, SeqStrINF str) throws Exception;
        // 删除当前串中从序号begin开始到序号end-1为止的子串
        public SeqStrINF strDelete(int begin, int end) throws Exception;
        // 把str串连接到当前串的后面
        public SeqStrINF strConcat(SeqStrINF str) throws Exception;
        // 将当前串与目标串str进行比较
        public int strCompare(SeqStrINF str) throws Exception;
        // 在当前串中从begin为止开始搜索与str相等的字符串
        public int strIndexOf(SeqStrINF str, int begin) throws Exception;
        // 输出顺序串中的所有元素
        public void strTraverse() throws Exception;
    }
    • 实现类:
    package bigjun.iplab.sequenceString;
    
    public class SeqString implements SeqStrINF{
        
        private char[] strElem;
        private int curlength;
        
        // 构造方法1:构造一个空串
        public SeqString() {
            strElem = new char[0];   
            curlength = 0;
        }
        
        // 构造方法2:以字符串常量构造串对象
        public SeqString(String str) {
            char[] tempCharArray = str.toCharArray();
            strElem = tempCharArray;     
            curlength = tempCharArray.length;
        }
        
        // 构造方法3:以字符数组构造串对象
        public SeqString(char[] strValue) {
            strElem = new char[strValue.length];    
            for (int i = 0; i < strValue.length; i++) {
                strElem[i] = strValue[i];
            }
            curlength = strValue.length;
        }
    
        public boolean isstrEmpty() {
            return curlength==0;
        }
    
        public void strClear() {
            curlength = 0;
        }
    
        public int strLength() {
            return curlength;
        }
    
        public char charAt(int index) throws Exception {
            if ((index < 0) || (index >= curlength)) {
                throw new Exception("索引值超出范围,无法给出对应字符");
            }
            return strElem[index];
        }
    
        public SeqStrINF strSubstr(int begin, int end) throws Exception {
            if (begin < 0 || end > curlength || begin > end) 
                throw new Exception("取子字符串操作参数值设定不合法");
            if (begin == 0 && end == curlength) {
                return this;
            }else {
                char[] buffer = new char[end - begin];
                for (int i = 0; i < buffer.length; i++) {
                    buffer[i] = this.strElem[i + begin];
                }
                return new SeqString(buffer);       // 调用构造函数,返回SeqString类型的字符串数组
            }
        }
        
        // 扩充字符串存储空间,如果当前数组已经满了,就要使用此函数来扩充数组
        public void allocate(int newCapacity) {
            char[] temp = strElem;
            strElem = new char[newCapacity];
            for (int i = 0; i < temp.length; i++) {
                strElem[i] = temp[i];
            }
        }
    
        public SeqStrINF strInsert(int offset, SeqStrINF str) throws Exception {
            if (offset < 0 || offset > curlength ) 
                throw new Exception("插入操作参数值设定不合法");
            int len = str.strLength();
            int newCount = this.curlength + len;
            if (newCount > strElem.length)      // 如果插入后的字符串总长度超过最大值,就要扩充可用数组长度
                allocate(newCount);
            for (int i = this.curlength - 1; i >= offset; i--)  // 将第offset后面的字符向后移动len
                strElem[len + i] = strElem[i];
            for (int i = 0; i < len; i++) 
                strElem[offset + i] = str.charAt(i);     // 将str字符串插入到原来的字符串中
            this.curlength = newCount;
            return this;
        }
    
        public SeqStrINF strDelete(int begin, int end) throws Exception {
            if (begin < 0 || end > curlength || begin > end) 
                throw new Exception("删除操作参数值设定不合法"); 
            for (int i = 0; i < curlength - end; i++)    // 从end开始至串尾的子串向前移动从begin开始的位置
                strElem[begin + i] = strElem[end + i];
            curlength = curlength - (end - begin);
            return this;
        }
    
        public SeqStrINF strConcat(SeqStrINF str) throws Exception {
            return strInsert(curlength, str);
        }
    
        public int strCompare(SeqStrINF str) throws Exception {
            int len1 = curlength;
            int len2 = str.strLength();
            int n = Math.min(len1, len2);
            char[] s1 = strElem;
            char[] s2 = new char[len2];
            for (int i = 0; i < s2.length; i++) {
                s2[i] = str.charAt(i);
            }
            int k = 0;
            while (k < n) {
                char ch1 = s1[k];
                char ch2 = s2[k];
                if (ch1 != ch2) 
                    return ch1 - ch2;      // 返回第一个不相等字符的数值差
                k++;
            }
            return Math.max(len1, len2) - n;      // 返回两个字符串长度差的绝对值
        }
    
        public int strIndexOf(SeqStrINF str, int begin) throws Exception {
            if (begin < 0  || begin > curlength) 
                throw new Exception("索引子字符串操作参数值设定不合法"); 
            int n = curlength;
            int m = str.strLength();
            int i = begin;
            while (i <= n - m) {
                SeqString str1 = (SeqString) strSubstr(i, i + m);
                if (str1.strCompare(str) != 0) {
                    ++i;
                } else {
                    return i;             // 返回在主串中的索引值
                }
            }
            return 0;                    // 没有子串与str相等,返回0
        }
    
        public void strTraverse() throws Exception {
            for (int i = 0; i < curlength; i++) {
                System.out.print(strElem[i]);
            }
            System.out.println();
        }
        
        public static void main(String[] args) throws Exception {
            SeqString str1 = new SeqString("abcd");
            System.out.print("str1字符串的输出: ");
            str1.strTraverse();
            
            char cha[] = {'e','f','g','h','i','j','k'};
            SeqString str2 = new SeqString(cha);
            System.out.print("str2字符串的输出: ");
            str2.strTraverse();
            System.out.println("str2是否为空: " + str2.isstrEmpty());
            System.out.println("str2此时的长度为: " + str2.strLength());
            System.out.println("str2数组下标为2的字符为: " + str2.charAt(2));
            
            System.out.println("str2和str1比大小的结果为: " + str2.strCompare(str1));
            
            System.out.print("str2数组下标为2-5(不包括5)的子字符串为: ");
            SeqString str3 = (SeqString) str2.strSubstr(2, 5);
            str3.strTraverse();
            
            System.out.print("在str2的第0个位置前面插入str1所得的字符串str4为: ");
            SeqString str4 = (SeqString) str2.strInsert(0, str1);
            str4.strTraverse();
            
            System.out.println("str4和str1比大小的结果为: " + str4.strCompare(str1));
            
            System.out.print("在str4的第6个位置前面插入str1所得的字符串str5为: ");
            SeqString str5 = (SeqString) str4.strInsert(0, str1);
            str5.strTraverse();
            
            System.out.print("删除str5的前七个位置的字符所得的字符串str6为: ");
            SeqString str6 = (SeqString) str5.strDelete(0, 8);
            str6.strTraverse();
            
            System.out.print("在str6的后面连接str1所得的字符串str7为: ");
            SeqString str7 = (SeqString) str6.strConcat(str1);
            str7.strTraverse();
            
            System.out.print("在清空str7后,");
            str7.strClear();
            System.out.print("str7是否为空: " + str7.isstrEmpty());
            System.out.println("。 str7此时的长度为: " + str7.strLength());
            
            System.out.print("在清空str1后,");
            str1.strClear();
            System.out.print("str1是否为空: " + str1.isstrEmpty());
            System.out.println("。 str1此时的长度为: " + str1.strLength());
            
            SeqString string1 = new SeqString("abcd");
            SeqString string2 = new SeqString("dadfdaabcdedad");
            System.out.print("string2中数组下标为0之后第一次存在string1的下标位置为: ");
            System.out.println(string2.strIndexOf(string1, 0));
            
            System.out.print("string2中数组下标为7之后第一次存在string1的下标位置为: ");
            System.out.println(string2.strIndexOf(string1, 7));
        }
    
    }
    • 输出:
    str1字符串的输出: abcd
    str2字符串的输出: efghijk
    str2是否为空: false
    str2此时的长度为: 7
    str2数组下标为2的字符为: g
    str2和str1比大小的结果为: 4
    str2数组下标为2-5(不包括5)的子字符串为: ghi
    在str2的第0个位置前面插入str1所得的字符串str4为: abcdefghijk
    str4和str1比大小的结果为: 7
    在str4的第6个位置前面插入str1所得的字符串str5为: abcdabcdefghijk
    删除str5的前七个位置的字符所得的字符串str6为: efghijk
    在str6的后面连接str1所得的字符串str7为: efghijkabcd
    在清空str7后,str7是否为空: true。 str7此时的长度为: 0
    在清空str1后,str1是否为空: true。 str1此时的长度为: 0
    string2中数组下标为0之后第一次存在string1的下标位置为: 6
    string2中数组下标为7之后第一次存在string1的下标位置为: 0
  • 相关阅读:
    基础之实战猜年龄游戏
    基本运算符与if while详解:
    while循环练习:
    常量与格式化输出练习
    Flask基础(05)-->路由的基本定义
    Flask基础(04)-->相关配置参数
    Flask基础(03)-->创建第一个Flask程序
    Flask基础(02)-->搭建Flask项目虚拟环境
    Flask基础(01)-->Flask框架介绍
    Flask实战第61天:帖子板块过滤显示
  • 原文地址:https://www.cnblogs.com/BigJunOba/p/9200957.html
Copyright © 2011-2022 走看看