String常見函式總結

2021-09-09 08:45:19 字數 2045 閱讀 5266

一、string的建立

1、建立空的string

e.g.string s;

2、建立有內容的string

e.g.string s="good";

二、string函式

1、輸入一行字元

<1> getline(cin,a);//輸入一行字元

<2>getline(cin,a,c);//輸入到字元c為止的字元

注:cin 輸入不能含有空格和換行

2、函式(不常用)

<1>a.begin(); //返回字串a的起始位址

<2>a.end(); //返回字串a的結束位址

<3>a.size(); //返回字串a的長度

<4>a.length(); //返回字串a的長度

<5>a.empty(); //字元為空返回true,否則返回false

<6>stoi(a); //字串a轉換為int型別

<7>stol(a); //字串a轉換為long int型別

<8>stoul(a); //字串a轉換為unsigned long int型別

<9>stoll(a); //字串a轉換為unsigned long long int型別

<10>stof(a); //字串a轉換為float型別

<11>stod(a); //字串a轉換為double型別

<10>stold(a); //字串a轉換為long double型別

3、將c的函式用於c++

<1>c++ 使用c的函式標頭檔案需加c的標頭檔案

e.g. #include

#include

<2>printf(a.c_str()); //將字串a用printf輸出

<3>在c++中用c陣列

e.g.#include#include#include#include#includeusing namespace std; int main() { char a[100]; while(gets(a)) //c++中多例項輸入最後不用加!=eof { string b=a; cout《插入新的字串——使用insert()函式

e.g.string a,b,c; a="zxc"; b="asd"; string::iterator it; //定義迭代器 a.insert(it+1,b);//在字串a的第1個位置插入字串b b.insert(it+2,5);//在字串b的第2個位置插入字元5 cout《直接把字串賦值為空

e.g.s="";

<2>利用clear()函式刪除

e.g.s.clear();

<3>利用earse()方法刪除字串中的一段字串或目標字元

e.g.string a; a="abcd12"; //賦值 string::iterator it=a.begin();//定義迭代器 a.erase(it+2);//刪除第2個元素,從零開始計數 cout<6、元素的修改

利用replace()方法實現字串修改

e.g.string a,b; a="123456"; b="asdfgh";//賦值 a.replace(3,3,"we")//從第3個開始連續3個字元替換為"we" cout<7、元素的查詢

利用find()方法實現字元或字串的查詢

e.g.string a="we you we"; cout<結果:0

0429496725

8、元素的比較

利用compare()方法實現字串的比較

e.g.string a; a="we you we"; cout<比較規則:按照ascll碼表的順序對字串從前到後依次比較字元,順序大的那個字串較大。

實現常見的string函式

1.實現strcpy 1.實現strcpy char my strcpy char dest,const char src return ret 2.實現strcat 2.實現strcat 字串拼接 char my strcat char dest,const char src while dest...

string函式總結(3)

字串流處理 通過定義ostringstream和istringstream變數實現,標頭檔案中例如 string input hello,this is a test istringstream is input string s1,s2,s3,s4 assign函式能將字串 或資料串 的內容設定給...

string函式的常見方法

0.tolower用法 將字串轉換成小寫 string s hello string s1 s.tolower 記住字串的不可變性 console.writeline s1 1.trim的用法 用來去除字串兩邊的空白 2.split函式 用來分隔陣列的函式 常見幾種型別 string split p...