string
建立
建立一個字串或者字串陣列如下
用 cin 輸入,可以讀一整串字元直到空格或換行才結束
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
string strs[N];
cin >> s;
for (int i = 0; i < N; i ++ )
{
cin >> strs[i];
}
cout << s << endl;
for (int i = 0; i < N; i ++ )
{
cout << strs[i] << endl;
}
return 0;
}
訪問大小
.size() 和 .length() 可以訪問字串的長度
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s.size() << endl;
return 0;
}
開頭與結尾
.begin()是開頭的地址
.end()是結尾的地址
插入
.push_back() 可以尾插
.insert() 可以精確插入,其中放插入的位置和插入的字元內容
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s << endl;
s.push_back('5');
cout << s << endl;
s.insert(s.begin(), '0');
cout << s << endl;
return 0;
}
刪除
.erase(),裡面放地址
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s << endl;
s.erase(s.begin());
cout << s << endl;
return 0;
}
查詢
find(),裡面放字串或者字元,返回下標數字
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s << endl;
cout << s.find('1') << endl;
return 0;
}
下面是放字元的情況
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s << endl;
cout << s.find("23") << endl;
return 0;
}
擷取
substr(), 放兩個數,一個是下標,一個是擷取的長度
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s;
cin >> s;
cout << s << endl;
s = s.substr(2, 5);
cout << s << endl;
return 0;
}
比較
string會預設按字典序比較,由高位向低位去比較
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s1 = "123456", s2 = "12345";
cout << (s1 > s2) << endl;
s1 = "12345", s2 = "12346";
cout << (s1 > s2) << endl;
return 0;
}
拼接
#include <iostream>
using namespace std;
const int N = 9;
int main()
{
string s1 = "123456", s2 = "789";
string s3 = s1 + s2;
cout << s3 << endl;
return 0;
}
反轉
reverse(開始地址, 結束地址)可以反轉內容