有些人更喜欢使用“绳索”数据结构来存储无限长度的字符串,而不是连续的字符串(C 字符串)。
简化的绳索可以定义为:
#include <stdio.h>
struct non_leaf_rope_node{
char zero;
union rope* left_substring;
union rope* right_substring;
// real rope implementations have a few more items here
};
#define rope_leaf_max ( sizeof( struct non_leaf_rope_node ) )
typedef union rope {
char rope_data[ rope_leaf_max ];
struct non_leaf_rope_node pointers;
} rope;
void print( union rope *node ){
if( node->rope_data[0] != '\0' ){
// short literal data
fputs( node->rope_data, stdout );
}else{
// non-root node
print( node->pointers.left_substring );
print( node->pointers.right_substring );
};
};
// other details involving malloc() and free() go here
int main(void){
rope left = { "Hello," };
rope right = { " World!" };
rope root = {0,0,0};
root.pointers.left_substring = &left;
root.pointers.right_substring = &right;
print( &root );
return 0;
};
少于rope_leaf_max 个字符的rope 与以null 结尾的C 字符串存储相同。包含超过rope_leaf_max 个字符的rope 存储为根non_leaf_rope_node 指向左右子字符串,(可能依次指向左右子子字符串),最终指向叶节点,叶节点每个都包含完整字符串的至少一个字符。
绳索总是至少存储一个字符,因此我们总是可以判断:如果绳索节点的第一个字节非零,则该节点是存储文字字符的叶节点。如果绳索节点的第一个字节为零,则该节点存储指向左右子字符串的指针。(真正的绳索实现通常有第三种绳索节点)。
通常使用绳索比使用 C 字符串需要更少的总 RAM 空间。(包含诸如“纽约市”之类的短语的节点可以在一根绳索中重复使用多次,或者在某些实现中在两条绳索之间共享)。有时使用绳索比使用 C 字符串更快。