C++字符串函数与字符数组函数

C++ 字符串(string类)函数
首先明确 字符串是从第0位 开始存储的
即 string s="123"; s[0]==1;

string ss="0123456789";
string ss2;
1.求长度
int len=ss.length(); //求字符串ss的长度返回值赋给len
(此时len==10)
 
2.提取子串
string ss2;
ss2=ss.substr(pos);//返回从pos开始的(包括pos)的子串赋给ss2;
(例 ss2=ss.substr(8);//此时ss2=="89")

ss2=ss.substr(pos,len);//返回从pos开始的len位子串赋给ss2;
(例 ss2=ss.substr(1,2);//此时ss2=="12");

3.子串查找
int where=ss.find(ss2);//查找ss2在ss中的位置并返回ss2第一个字符在ss中的位置,若找不到则返回-1;
(例 ss2="23";int where=ss.find(ss2);//where==2
    ss2="00",int where=ss.find(ss2);//where==-1);

int where=ss.find(ss2,pos);//从ss的第pos(pos>=0)位开始查找,返回ss2在ss中的位置,若找不到则返回-1;
(例 ss2="78";int where=ss.find(ss2,7);//where==7
     ss2="78";int where=ss.find(ss2.8);//where==-1);
 ---------------------------------以上为手打,以下..囧rz-----------------------------------------

这3种 是字符串最常用的操作,几种不常用的如下
6. 插入字符串
   不是赋值语句。
   str1.insert(pos1,str2); //如str1.insert(2,str2)则str1=”heworldllo,”
    str1.insert(pos1,str2,pos2,len2);
    str1.insert(pos1,numchar,char); numchar是插入次数,char是要插入的字符。
7. 替换字符串
   str1.replace(pos1,str2);
   str1.replace(pos1,str2,pos2,len2);
8. 删除字符串
   str.erase(pos,len)
   str.clear();
9. 交换字符串
   swap(str1,str2);

 

字符数组:
一、用字符数组来存储字符串:
char st1[100],st2[100] ; //字符数组说明
cin>>st1>>st2;
long a,b;
输入:hello, world
则st1={‘h’,’e’,’l’,’l’,’o’,’,’,’\0’}
st2={‘w’,’o’,’r’,’l’,’d’,’\0}
字符’\0’为字符串结束标志
1. 字符数组长度
   strlen(st1); //如a=strlen(st1);b=strlen(st2); 则a=6,b=5
2. 字符数组比较
   不能直接比较,st1>st2是错误的,要用strcmp()函数
   strcmp(st1,st2); //st1=st2相等则输出0,st1<st2输出-1,st1>st2输出1
   strncmp(st1,st2,n);   把st1,st2的前n个进行比较。
3. 连接字符数组
   不能直接用st1=st1+st2;用strcat()函数
   strcat(st1,st2); //将st1和st2连接后赋给st1,本例连接后st1为”hello,world”
   strncat(st1,st2,n);   n表示连接上st2的前n个给st1,在最后不要加'\0'。
4. 替换
   strcpy(st1,st2); //用st2的值替换st1的值,字符数组不能如此赋值st1=st2或st1[]=st2[]都是错误的
   本例中st1值被替代为”world”
   strncpy(st1,st2,n); n表示复制st2的前n个给st1,在最后要加'\0'。
5. 其他函数
strchr(st1,ch) //ch为要找的字符。如strchr(st1,’e’);会截取出st1中以字母’e’开头的字符串,要用string类型的来存储,如string c1; c1=strchr(st1,’e’); 则c1为”ello”
   strspn(st1,st2); //返回st1起始部分匹配st2中任意字符的字符数。本例中”hello,”中的第一个字符’h’不能在”world”中找到匹配字符,因此返回值为0。如st1=”rose”;st2=”worse”;则返回值为4,因为rose在worse中都能找到匹配字符。
   strrev(); //颠倒字符串

转载于:https://www.cnblogs.com/xujian9502/archive/2012/01/04/2312431.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值