詳解C++字符串常用操作函數(shù)(查找、插入、截取、刪除等)
更新時間:2021年01月12日 09:50:32 作者:Bulut0907
這篇文章主要介紹了C++字符串常用操作函數(shù)(查找、插入、截取、刪除等),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
1. 字符串查找函數(shù)
1.1 find 函數(shù)
原型為:unsigned int find(const basic_string &str) const;
作用:查找并返回str在本串中第一次出現(xiàn)的位置,位置從0開始
例子如下:
#include <iostream> using namespace std; int main() { string str = "i love china. china love me"; string find_str = "love"; cout << str.find(find_str); // 2 return 0; }
2. 字符串插入函數(shù)
2.1 append
- 函數(shù)原型為:
string append(const char* s) ;
- 作用:將字符串s添加到本串尾,改變本串
- 例子如下:
#include <iostream> using namespace std; int main() { string str = "i love china. "; char append_str[] = "china love me"; cout << str.append(append_str) << endl; // i love china. china love me cout << str << endl; // i love china. china love me return 0; }
2.2 insert
- 函數(shù)原型為:
string & insert(unsigned int p0, const char * s);
- 作用:將s所指向的字符串插入在本串中位置p0之前,改變本串
- 例子如下:
#include <iostream> using namespace std; int main() { string str = "i love . china love me"; char insert_str[] = "china"; cout << str.insert(7, insert_str) << endl; // i love china. china love me cout << str << endl; // i love china. china love me return 0; }
3. 字符串截取函數(shù)
3.1 substr
- 函數(shù)原型為:
string substr(unsigned int pos, unsigned int n) const;
- 作用:取子串,取本串中位置pos開始的n個字符,構(gòu)成新的string類對象作為返回值
- 例子如下:
#include <iostream> using namespace std; int main() { string str = "i love china. china love me"; cout << str.substr(2, 22) << endl; // love china. china love return 0; }
4. 字符串刪除函數(shù)
4.1 函數(shù)
- 原型1為:
string & erase(unsigned int pos);
- 作用1:刪除本串pos位置及之后的所有字符,改變本串
- 函數(shù)原型2為:
string & erase(unsigned int pos, unsigned int n);
- 作用2:刪除本串pos位置及之后的共n個字符,改變本串
- 例子如下:
#include <iostream> using namespace std; int main() { string str1 = "i love china. china love me"; cout << str1.erase(12) << endl; // i love china cout << str1 << endl; // i love china string str2 = "i love china. china love me"; cout << str2.erase(7, 18) << endl; // i love me cout << str2 << endl; // i love me return 0; }
到此這篇關(guān)于C++字符串常用操作函數(shù)(查找、插入、截取、刪除等)的文章就介紹到這了,更多相關(guān)C++字符串操作函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
C++?JSON庫?nlohmann::basic_json::array?的用法示例詳解
nlohmann::json是一個C++的JSON庫,它提供了一種容易和直觀的方法來處理JSON數(shù)據(jù),nlohmann::json::array()是用來創(chuàng)建一個JSON數(shù)組的方法,這篇文章主要介紹了C++ JSON庫nlohmann::basic_json::array的用法,需要的朋友可以參考下2023-06-06C語言基于循環(huán)鏈表解決約瑟夫環(huán)問題的方法示例
這篇文章主要介紹了C語言基于循環(huán)鏈表解決約瑟夫環(huán)問題的方法,簡單描述了約瑟夫環(huán)問題并結(jié)合實例形式分析了C語言使用循環(huán)鏈表解決約瑟夫環(huán)問題的具體操作技巧,需要的朋友可以參考下2018-01-01基于C++實現(xiàn)kinect+opencv 獲取深度及彩色數(shù)據(jù)
本文的主要思想是Kinect SDK 讀取彩色、深度、骨骼信息并用OpenCV顯示,非常的實用,有需要的小伙伴可以參考下2015-12-12