串的基本操作的实现

1.求子串://用sub返回串S的第pos个字符起长度为len的字串

 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.ch[1]开始存

  Sub.length=len;

  return true;

 }

2.比较操作://若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;  //扫描过的所有字符都相同,则长度长的串更大

  }

3.定位操作://若主串S中存在与串T值相同的子串则返回它在函数中第一次出现的位置;否则函数值为0、

  int Index(S,T){

    int i=1,n=StrLength(S),m=StrLength(T);

    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相等的子串

  }

猜你喜欢

转载自www.cnblogs.com/c-s-d-n/p/12925298.html