一、string子串
c++中的字符串類型string提供了一些操作子串的方法,用於截取原字符串的一部分。其中substr方法是最常用的方法之一。
substr方法的使用格式如下:
string substr (size_t pos, size_t len) const;
其中,pos表示截取子串的起始位置,len表示要截取的子串的長度。
比如,對於字符串”hello, world!”,我們可以通過以下代碼來截取子串:
#include #include using namespace std; int main() { string str = "hello, world!"; string sub = str.substr(7, 5); cout << sub << endl; // 輸出 world return 0; }
二、c中string字符串
c語言中的字符串是以字符數組的形式存儲的,因此在進行字符串操作時需要使用字符數組相關的函數。如果需要在c++中使用c語言中的字符串,可以通過將字符數組轉化為c++中的string類型來進行操作。
以下代碼示例演示了從c語言字符串到c++string的轉換:
#include #include using namespace std; int main() { char c_str[] = "hello, world!"; string str(c_str); cout << str << endl; // 輸出 hello, world! return 0; }
三、c字符串轉string數組
在c++中,可以使用string的c_str方法將string類型轉換為c語言中的字符數組。這種轉換可以使得string類型的字符串在需要以字符數組作為參數的情況下也能夠被調用。
以下代碼示例演示了如何將string類型的字符串轉換為c語言中的字符數組:
#include #include using namespace std; int main() { string str = "hello, world!"; const char *c_str = str.c_str(); cout << c_str << endl; // 輸出hello, world! return 0; }
四、string字符串取子串
除了substr方法外,c++的string類型還提供了另外一種截取子串的方法,即使用[]運算符。使用[]運算符可以像操作普通數組一樣來操作字符串。下面是一個簡單的示例:
#include #include using namespace std; int main() { string str = "hello, world!"; string sub = str.substr(7, 5); string sub2 = str[7] + str[8] + str[9] + str[10] + str[11]; cout << sub << endl; // 輸出 world cout << sub2 << endl; // 輸出 world return 0; }
五、stringc里比較字符串
在c++中,string類型的字符串可以使用==和!=運算符進行比較。比較的結果為true或false。這種方式比較簡單直觀,並且可以避免字符串長度不一致導致的問題。
以下代碼演示了如何使用==和!=運算符來比較兩個string類型的字符串:
#include #include using namespace std; int main() { string str1 = "hello"; string str2 = "world"; if(str1 == str2) { cout << "字符串相等" << endl; } else { cout << "字符串不相等" << endl; } return 0; }
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/188455.html