//STL standard template libary 標(biāo)準(zhǔn)模(mu)板庫(kù) C++一部分,編譯器自帶
//Android NDK支持
//java.lang java.util包中API拇囊,java的一部分
這個(gè)東西毡惜,就相當(dāng)于是C++的一個(gè)插件代碼庫(kù)芯侥,里面有很多簡(jiǎn)化柑晒,或者說(shuō),跟JAVA非常類(lèi)似的元素宝与,NDK直接就支持這個(gè)庫(kù)喜滨,也就是說(shuō)捉捅,不需要在外面引包之類(lèi)的。 但是虽风,如果是用非CMAKE的形式開(kāi)發(fā)棒口,要用到STL里的元素,必須先申請(qǐng)需要使用STL辜膝,才行无牵。CMAKE則不需要作額外的申明。
如string厂抖,這個(gè)東西在C++中是沒(méi)有的茎毁,但在STL中定義了,就可以直接用,和JAVA幾乎一樣七蜘。
使用前谭溉,需要先引入string
#include<string>
using namespace std;
void main()
{
? ?//string由c字符串衍生過(guò)來(lái)的
? ?string s1 = "craig david";
? ?string s2("7 days");
? ?string s3 = s2;
? ?string s4(10,'a');
? ?cout << s4 << endl;
? ?system("pause");
}
這個(gè)string,就是STL中義的,是不是跟JAVA很像了橡卤?扮念?
還包括了一些方法,如 string.length();?
但這個(gè)string和C中的char* 還是不一樣的!故是需要轉(zhuǎn)換的碧库!
void main()
{
? ?//string -> char*
? ?string s1 = "walking away";
? ?const char* c = s1.c_str();
? ?printf("%s\n",c);
? ?//
? ?string s2 = c;
? ?//string->char[]
? ?//從string中賦值字符到char[]
? ?char arr[50] = {0};
? ?s1.copy(arr,4,0);
? ?cout << arr << endl;
? ?system("pause");
}
可以看出柜与,const char* c = s1.c_str(); 這個(gè)方法,可以將string型轉(zhuǎn)為char*型嵌灰,前面要加一個(gè)常量弄匕,不然會(huì)報(bào)錯(cuò)
string的拼接
string s1 = "alan";
string s2 = "jackson";
//1.
string s3 = s1 + s2;
string s4 = " pray";
//2.
s3.append(s4);
//字符串查找替換
void main()
{
string s1 = "apple google apple iphone";
//從0開(kāi)始查找"google"的位置
int idx = s1.find("google", 0);
cout << idx << endl;
//統(tǒng)計(jì)apple出現(xiàn)的次數(shù)
int idx_app = s1.find("apple",0);
//npos大于任何有效下標(biāo)的值
int num = 0;
while (idx_app != string::npos)
{
num++;
cout << "找到的索引:" << idx_app << endl;
idx_app+=5;
idx_app = s1.find("apple", idx_app);
}
cout << num << endl;
system("pause");
}
替換
void main()
{
string s1 = "apple google apple iphone";
//0-5(不包含5)替換為jobs
s1.replace(0, 5, "jobs");
cout << s1 << endl;
//所有apple替換為jobs
int idx = s1.find("apple", 0);
while (idx != string::npos)
{
s1.replace(idx, 5, "jobs");
idx += 5;
idx = s1.find("apple", idx);
}
cout << s1 << endl;
system("pause");
}
//刪除(截取)和插入
void main()
{
string s1 = "apple google apple iphone";
//刪除g沽瞭,找到g所在的指針
string::iterator it = find(s1.begin(),s1.end(),'g');
//只能刪除一個(gè)字符
s1.erase(it);
//開(kāi)頭末尾插入字符串
s1.insert(0, "macos");
s1.insert(s1.length(), " facebook");
cout << s1 << endl;
system("pause");
}
//大小寫(xiě)轉(zhuǎn)換
void main()
{
? ?string s1 = "JASON";
? ?//原始字符串的起始地址迁匠,原始字符串的結(jié)束地址, 目標(biāo)字符串的起始地址, 函數(shù)名稱(chēng)
? ?transform(s1.begin(), s1.end()-1,s1.begin(), tolower);
? ?cout << s1 << endl;
? ?transform(s1.begin(), s1.end() - 1, s1.begin(), toupper);
? ?cout << s1 << endl;
? ?system("pause");
}