数据结构之 -- 串

    今天写一下串这个结构

    串是字符串的简称,是一种特殊的线性表,是处理非数值计算问题的主要对象。串也是非常有用的,我们非常熟悉和非常有名的编辑器VIM也主要是在倒腾串。

    串也有多种存储结构,包括:顺序存储结构,堆存储结构,和链式存储结构。

    顺序存储结构的实现就比较简单了,就是一个定义一个大小固定的字符数组,当然它的劣势也是很明显的,因为串的大小是非常不固定的,所以事先定义

  一个很大的数组的话无非会导致一些内存空间的利用率非常底下,浪费严重。

    堆结构就是随时分配空间,用完再释放掉,基本不会造成浪费,是我最喜欢的结构。主要用到malloc()函数和realloc()函数。

    链式存储结构就是一个字符类型的链表,咋说呢,不好也不坏,还行吧。

    

       今天我写一个堆结构的串。

    先来总结一下串应该有的操作:

    1.初始化串

    2.求串长

    3.取子串

    4.格式化遍历(打印)串

    5.定位串(查找某一子串是否存在)

    6.串了连接

    7.串比较

    8.判串空(我们不单独实现它,而是通过求串长来实现)

    9.串替换

    10.串赋值

    11.串插入

    12.串删除

  大家也能看出来,串是可以整出很多花招的

  我只实现串的部分操作

   

  定义串结构

  

/* define a string */  

 const int LINELENGTH = 50;

 struct string{
          int  length;
          char *ch;
  };

  1.初始化串

/* init_string */
  int init_string( struct string *s,char *str )
  {
          char *temp_str = str;
          s->ch = malloc( sizeof(char) );
          s->length = 0;
  
          while( *temp_str != ''){
                  if( !(s->ch = realloc( s->ch,sizeof(char) + s->length )) ){
                          printf("failure : error of memory allocation.
");
                          return 0;
                  }                               
                  s->ch[s->length] = *temp_str ++;
                  s->length ++;
          }
  
          s->ch[s->length] = '';
  
          return 1;
  }

  2.求串长

  

 /* getting string length */
  int get_str_len(struct string *s)
  {
          return s->length;
  }

  4.格式化遍历(打印)串

  

/* print string */
  int print_ch( struct string *s)
  {
          char *p = s->ch;
          int cnt = 0;
  
          while( *p != '' ){
                  if( *p == '
' ){
                          cnt = cnt + ( LINELENGTH - cnt%LINELENGTH);
                          p ++;
                  }
                  if(  cnt % LINELENGTH == 0 ){
                          if( cnt != 0 ){
                                  printf("
%3d: ",cnt/LINELENGTH + 1);
                          }else{
                                  printf("%3d: ",1);
                          }
                  };
                  cnt ++;
                  if( *p != '
' ){
                          printf("%c",*p ++);
                  }
          }
  
          putchar('
');
          for( cnt=0;cnt<LINELENGTH+10;cnt++ ){
                  putchar('-');
          }
          return 1;
  }

  我这个打打印串的函数是按照一定格式输出的,带有行号输出

  我从cnn上面摘抄了一段支持普朗特的新闻测试了一下

  

  

  其它的功能今天没时间写了。。。

原文地址:https://www.cnblogs.com/zhangte/p/5166776.html