数据结构和算法(02)---字符串(c++)
文章目錄
- 目錄
- 一.c風格的字符串與操作函數
- 1.c風格字符串
- 2.c風格字符串處理函數
- 二.c++中的字符串與操作函數
- 1.c++中的string類
- 2.string類的基本操作
- 3.string類的操作匯總
目錄
- 數據結構:
- 邏輯結構:數組,棧,隊列,字符串,樹,圖
- 存儲結構:順序存儲,鏈式存儲
- C++常用的數據結構有:string , stack , queue , deque , vector , list , map , iterators.
參考博客
注意
可以將字符串看成一種特殊的順序表,特殊之處在于表的節點只能存儲字符串。由于字符串相鄰元素的位置是由關系的,即順序關系,不建議用鏈式存儲結構存儲
一.c風格的字符串與操作函數
1.c風格字符串
C風格的字符串起源于 C 語言,并在 C++ 中繼續得到支持。
字符串實際上是使用 null 字符 ‘\0’ 終止的一維字符數組。
因此,一個以 null 結尾的字符串,包含了組成字符串的字符。
下面的聲明和初始化創建了一個 “Hello” 字符串。
由于在數組的末尾存儲了空字符,所以字符數組的大小比單詞 “Hello” 的字符數多一個。
以下是 C/C++ 中定義的字符串的內存表示:
其實,您不需要把 null 字符放在字符串常量的末尾。
C++ 編譯器會在初始化數組時,自動把 ‘\0’ 放在字符串的末尾。
讓我們嘗試輸出上面的字符串:
#include <iostream> using namespace std; int main (){char s1[6] = {'H', 'e', 'l', 'l', 'o', '\0'};char s2[6] = {'H', 'e', 'l', 'l', 'o'};char s3[] = "hello"; //編譯器會根據字符串長度的大小初始化字符數組的cout << s1 << endl;cout << s2 << endl;cout << s3 << endl; }Hello
Hello
hello
2.c風格字符串處理函數
C++ 中有大量的函數用來操作以 null 結尾的字符串
下面的實例使用了上述的一些函數:
二.c++中的字符串與操作函數
1.c++中的string類
C++ 標準庫提供了 string 類類型,支持上述所有的操作,另外還增加了其他更多的功能。我們將學習 C++ 標準庫中的這個類,現在讓我們先來看看下面這個實例:
#include <iostream> #include <string>using namespace std;int main () {string str1 = "Hello";string str2 = "World";string str3;int len ;// 復制 str1 到 str3str3 = str1;cout << "str3 : " << str3 << endl;// 連接 str1 和 str2str3 = str1 + str2;cout << "str1 + str2 : " << str3 << endl;// 連接后,str3 的總長度len = str3.size();cout << "str3.size() : " << len << endl; }str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
2.string類的基本操作
string類提供了一系列針對字符串的操作:
運行程序輸出:
hello word!!
the len of str1 is:12
hello word!! Itis a string example!! the len of string is:37 str2 is:hello word!! append str:hello word!! Its a demo!!!
the pos of llo is:2
str1 is :he word!! It`s a demo!!!
the fist pos is:2 the last pos is:9
lo world
3.string類的操作匯總
字符串操作函數
這里是C++字符串的重點,把各種操作函數羅列出來:
a) =,assign() //賦以新值
b) swap() //交換兩個字符串的內容
c) +=,append(),push_back() //在尾部添加字符
d) insert() //插入字符
e) erase() //刪除字符
f) clear() //刪除全部字符
g) replace() //替換字符
h) + //串聯字符串
i) ==,!=,<,<=,>,>=,compare() //比較字符串
j) size(),length() //返回字符數量
k) max_size() //返回字符的可能最大個數
l) empty() //判斷字符串是否為空
m) capacity() //返回重新分配之前的字符容量
n) reserve() //保留一定量內存以容納一定數量的字符
o) [ ], at() //存取單一字符
p) >>, getline() //從stream讀取某值
q) << //將謀值寫入stream
r) copy() //將某值賦值為一個C_string
s) c_str() //將內容以C_string返回
t) data() //將內容以字符數組形式返回
u) substr() //返回某個子字符串
v)查找函數
w)begin() end() //提供類似STL的迭代器支持
x) rbegin() rend() //逆向迭代器
y) get_allocator() //返回配置器
總結
以上是生活随笔為你收集整理的数据结构和算法(02)---字符串(c++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python外卷(10)--取整
- 下一篇: 《C++ Primer 5th》笔记(9