數據結構(十五)串的順序存儲結構(順序串)


  一、串的定義:串(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("\n");
}


int main()
{
    
    int i,j;
    Status k;
    char s;
    String t,s1,s2;
    printf("請輸入串s1: ");
    
    k=StrAssign(s1,"abcd");
    if(!k)
    {
        printf("串長超過MAXSIZE(=%d)\n",MAXSIZE);
        exit(0);
    }
    printf("串長為%d 串空否?%d(1:是 0:否)\n",StrLength(s1),StrEmpty(s1));
    StrCopy(s2,s1);
    printf("拷貝s1生成的串為: ");
    StrPrint(s2);
    printf("請輸入串s2: ");
    
    k=StrAssign(s2,"efghijk");
    if(!k)
    {
        printf("串長超過MAXSIZE(%d)\n",MAXSIZE);
        exit(0);
    }
    i=StrCompare(s1,s2);
    if(i<0)
        s='<';
    else if(i==0)
        s='=';
    else
        s='>';
    printf("串s1%c串s2\n",s);
    k=Concat(t,s1,s2);
    printf("串s1聯接串s2得到的串t為: ");
    StrPrint(t);
    if(k==FALSE)
        printf("串t有截斷\n");
    ClearString(s1);
    printf("清為空串后,串s1為: ");
    StrPrint(s1);
    printf("串長為%d 串空否?%d(1:是 0:否)\n",StrLength(s1),StrEmpty(s1));
    printf("求串t的子串,請輸入子串的起始位置,子串長度: ");

    i=2;
    j=3;
    printf("%d,%d \n",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 \n",i,j);


    StrDelete(t,i,j);
    printf("刪除后的串t為: ");
    StrPrint(t);
    i=StrLength(s2)/2;
    StrInsert(s2,i,t);
    printf("在串s2的第%d個字符之前插入串t后,串s2為:\n",i);
    StrPrint(s2);
    i=Index(s2,t,1);
    printf("s2的第%d個字母起和t第一次匹配\n",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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM