一、c截取字元串
c語言中可以使用strtok函數截取字元串,但是在c++中,可以使用string中的substr函數實現截取字元串。
substr函數接受兩個參數,第一個參數為截取的起始下標,第二個參數為要截取的長度。如果只傳入一個參數,則截取剩餘的全部字元串。
#include #include using namespace std; int main() { string str = "hello world"; string sub_str = str.substr(6, 5); cout << sub_str << endl; // "world" return 0; }
二、cstring截取字元串
cstring是c++中對於c語言中char*類型字元串的封裝。使用cstring截取字元串可以使用類似於c語言中的指針進行截取。
可以通過對於字元串名的取地址,來獲取字元串的首地址。利用指針可以直接操作字元串。
#include #include using namespace std; int main() { char str[] = "hello world"; char* sub_str = str + 6; cout << sub_str << endl; // "world" return 0; }
三、截取字元串string
在string中截取字元串也可以使用substr函數,其實現方式與c截取字元串類似。
需要注意的是,在實際使用中,可以採用string對象的方式截取字元串。
#include #include using namespace std; int main() { string str = "hello world"; string sub_str = string(str, 6, 5); cout << sub_str << endl; // "world" return 0; }
四、c截取字元串的指定字元
c語言中使用strchr函數來查找字元串中的指定字元,而在c++中可以使用find函數來實現。
find函數返回指定字元在字元串中第一次出現的位置。
#include #include using namespace std; int main() { string str = "hello world"; int index = str.find('w'); string sub_str = str.substr(index); cout << sub_str << endl; // "world" return 0; }
五、std::string截取字元串
std::string和string的使用差不多,只是可能需要加上命名空間std::來使用。
std::string的substr函數用法和普通的string類似。
#include #include using namespace std; int main() { std::string str = "hello world"; std::string sub_str = str.substr(6, 5); cout << sub_str << endl; // "world" return 0; }
六、string截取指定字元串
使用string的find函數獲取子字元串在主字元串中的位置,再通過substr函數截取。
#include #include using namespace std; int main() { string str = "hello world"; string sub_str = "world"; int index = str.find(sub_str); string result = str.substr(index); cout << result << endl; // "world" return 0; }
七、string類型截取字元串
可以使用string的find函數和substr函數實現截取字元串。
#include #include using namespace std; int main() { string str = "hello world"; string sub_str = "wo"; int start = str.find(sub_str)+sub_str.size(); string result = str.substr(start); cout << result << endl; // "rld" return 0; }
八、cstring截取到指定字元
和c語言中類似,使用strchr函數查找指定字元的位置,然後進行指針的操作實現字元串的截取。
#include #include using namespace std; int main() { char str[] = "hello, world"; char* sub_str = strchr(str, ','); *sub_str = '\0'; cout << str << endl; // "hello" return 0; }
九、string截取兩個字元串之間的值
可以使用string的find_first_of和find_last_of函數查找兩個字元串的位置,然後通過substr函數進行截取。
#include #include using namespace std; int main() { string str = "hello world"; string start_str = "h"; string end_str = "d"; int start = str.find_first_of(start_str)+1; int end = str.find_last_of(end_str); string result = str.substr(start, end-start); cout << result << endl; // "ello worl" return 0; }
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/242399.html