1 C++ 字符串(string类)函数 2 首先明确 字符串是从第0位 开始存储的 3 即 string s="123"; s[0]==1; 4 5 string ss="0123456789"; 6 string ss2; 7 1.求长度 8 int len=ss.length(); //求字符串ss的长度返回值赋给len 9 (此时len==10) 10 11 2.提取子串 12 string ss2; 13 ss2=ss.substr(pos);//返回从pos开始的(包括pos)的子串赋给ss2; 14 (例 ss2=ss.substr(8);//此时ss2=="89") 15 16 ss2=ss.substr(pos,len);//返回从pos开始的len位子串赋给ss2; 17 (例 ss2=ss.substr(1,2);//此时ss2=="12"); 18 19 3.子串查找 20 int where=ss.find(ss2);//查找ss2在ss中的位置并返回ss2第一个字符在ss中的位置,若找不到则返回-1; 21 (例 ss2="23";int where=ss.find(ss2);//where==2 22 ss2="00",int where=ss.find(ss2);//where==-1); 23 24 int where=ss.find(ss2,pos);//从ss的第pos(pos>=0)位开始查找,返回ss2在ss中的位置,若找不到则返回-1; 25 (例 ss2="78";int where=ss.find(ss2,7);//where==7 26 ss2="78";int where=ss.find(ss2.8);//where==-1); 27 ---------------------------------以上为手打,以下..囧rz----------------------------------------- 28 29 这3种 是字符串最常用的操作,几种不常用的如下 30 6. 插入字符串 31 不是赋值语句。 32 str1.insert(pos1,str2); //如str1.insert(2,str2)则str1=”heworldllo,” 33 str1.insert(pos1,str2,pos2,len2); 34 str1.insert(pos1,numchar,char); numchar是插入次数,char是要插入的字符。 35 7. 替换字符串 36 str1.replace(pos1,str2); 37 str1.replace(pos1,str2,pos2,len2); 38 8. 删除字符串 39 str.erase(pos,len) 40 str.clear(); 41 9. 交换字符串 42 swap(str1,str2); 43 44 45 46 字符数组: 47 一、用字符数组来存储字符串: 48 char st1[100],st2[100] ; //字符数组说明 49 cin>>st1>>st2; 50 long a,b; 51 输入:hello, world 52 则st1={‘h’,’e’,’l’,’l’,’o’,’,’,’\0’} 53 st2={‘w’,’o’,’r’,’l’,’d’,’\0} 54 字符’\0’为字符串结束标志 55 1. 字符数组长度 56 strlen(st1); //如a=strlen(st1);b=strlen(st2); 则a=6,b=5 57 2. 字符数组比较 58 不能直接比较,st1>st2是错误的,要用strcmp()函数 59 strcmp(st1,st2); //st1=st2相等则输出0,st1<st2输出-1,st1>st2输出1 60 strncmp(st1,st2,n); 把st1,st2的前n个进行比较。 61 3. 连接字符数组 62 不能直接用st1=st1+st2;用strcat()函数 63 strcat(st1,st2); //将st1和st2连接后赋给st1,本例连接后st1为”hello,world” 64 strncat(st1,st2,n); n表示连接上st2的前n个给st1,在最后不要加'\0'。 65 4. 替换 66 strcpy(st1,st2); //用st2的值替换st1的值,字符数组不能如此赋值st1=st2或st1[]=st2[]都是错误的 67 本例中st1值被替代为”world” 68 strncpy(st1,st2,n); n表示复制st2的前n个给st1,在最后要加'\0'。 69 5. 其他函数 70 strchr(st1,ch) //ch为要找的字符。如strchr(st1,’e’);会截取出st1中以字母’e’开头的字符串,要用string类型的来存储,如string c1; c1=strchr(st1,’e’); 则c1为”ello” 71 strspn(st1,st2); //返回st1起始部分匹配st2中任意字符的字符数。本例中”hello,”中的第一个字符’h’不能在”world”中找到匹配字符,因此返回值为 0。如st1=”rose”;st2=”worse”;则返回值为4,因为rose在worse中都能找到匹配字符。 72 strrev(); //颠倒字符串