C++字符串详解(二)访问与拼接
生活随笔
收集整理的這篇文章主要介紹了
C++字符串详解(二)访问与拼接
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
訪問字符串中的字符
#include <iostream> #include <string> using namespace std; int main(){string s = "1234567890";for(int i=0,len=s.length(); i<len; i++){cout<<s[i]<<" ";}cout<<endl;s[5] = '5';cout<<s<<endl;return 0; }字符串的拼接
有了 string 類,我們可以使用+或+=運算符來直接拼接字符串,非常方便,再也不需要使用C語言中的 strcat()、strcpy()、malloc() 等函數來拼接字符串了,再也不用擔心空間不夠會溢出了。
用+來拼接字符串時,運算符的兩邊可以都是 string 字符串,也可以是一個 string 字符串和一個C風格的字符串,還可以是一個 string 字符串和一個字符數組,或者是一個 string 字符串和一個單獨的字符。請看下面的例子
#include <iostream> #include <string> using namespace std; int main(){string s1 = "first ";string s2 = "second ";char *s3 = "third ";char s4[] = "fourth ";char ch = '@';string s5 = s1 + s2;string s6 = s1 + s3;string s7 = s1 + s4;string s8 = s1 + ch;cout<<s5<<endl<<s6<<endl<<s7<<endl<<s8<<endl;return 0; }總結
以上是生活随笔為你收集整理的C++字符串详解(二)访问与拼接的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++友元函数和友元类(三)
- 下一篇: C++字符串详解(三) 字符串的增删改