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(); //顛倒字符串


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM