文档详情

第四章 数组、串和广义表(2).ppt

发布:2017-08-02约7.27千字共51页下载文档
文本预览下载声明
2.4 字符串;1、字符串字符的数目n称为串的长度。零个字符的串称为空串;通常以两个相邻的双引号来表示空串(Null string),如:s=“”,它的长度为零; 2、仅由空格组成的的串称为空格串,如:s=“ ”; 3、若串中含有空格,在计算串长时,空格应计入串的长度中,如:s=“I’m a student” 的长度为13。 4、在C语言中,串是用字符数组实现的。用单引号引起来的单个字符与单个字符的串是不同的, 如s1=‘a’与s2=“a”两者是不同的,s1表示字符,而s2表示字符串。;1、字符串复制 int strcpy(char *to, char *from) 将字符串from复制到字符串to. 2、字符串部分复制 int strncpy(char *to, char *from, int n) 将字符串from的前n个字符覆盖字符串to的前n个 字符. 3、字符串连接 int strcat(char *s1, char *s2) 将字符串s2连接在字符串s1之后,构成一个首指 针为s1的字符串。 4、将一字符串的特定数量字符连接到另一字符串。 int strncat(char *s1, char *s2, int n) 将字符串s2的前n个字符连接在字符串s1之后。;5、计算字符串的长度 int strlen(const char *s) 返回字符串中字符的个数 6、字符串比较大小 int strcmp(char *s,char *t) 如果st,返回负数,如果s=t,返回0,如果 st,返回正数。 其他:strchr,strcspn, strrchr, strpbrk, ……;字符串的实现; #define DefaultSize 256 typedef struct { char *ch; int maxSize; int curLength; } SeqString; void overflowProcess() { char * newAaddress = new char[2*maxSize]; if (newAddress == NULL) { cerr “Memory Allocation Error” endl; exit(1); } int n = maxSize = 2*maxSize; char *srcptr = ch; char *destptr = newAddress; while (n--) *destptr++ = *srcptr++; del [] ch; ch = newAddress; };字符串抽象数据类型和类定义; String operator ( ) ( int pos, int len ); //求子串 int operator == ( const String ob ) const { return strcmp (ch, ob.ch) == 0; } //串的比较 int operator != ( const String ob ) const { return strcmp (ch, ob.ch) != 0; } //串的比较 int operator ! ( ) const { return curLen == 0; } //判断是否空串 String operator = ( const String ob ); //串赋值 String operator += ( const String ob ); //串连接 char operator [ ] ( int i ); //求串中指定位置字符 int Find ( String pat ) const; //查找子串 };字符串部分操作的实现;String::String ( const char *init ) { //复制构造函数: 从已有字符数组*init复制 ch = new char[maxLen+1]; if ( !ch ){ cout “Allocation Error\n”; exit(1); } curLen = strlen (init); strcpy ( ch, init ); };S
显示全部
相似文档