C++ STL标准库 string

//STL standard template libary 标准模(mu)板库 C++一部分,编译器自带

//Android NDK支持

//java.lang java.util包中API,java的一部分

这个东西,就相当于是C++的一个插件代码库,里面有很多简化,或者说,跟JAVA非常类似的元素,NDK直接就支持这个库,也就是说,不需要在外面引包之类的。 但是,如果是用非CMAKE的形式开发,要用到STL里的元素,必须先申请需要使用STL,才行。CMAKE则不需要作额外的申明。

如string,这个东西在C++中是没有的,但在STL中定义了,就可以直接用,和JAVA几乎一样。

使用前,需要先引入string

#include

using namespace std;

void main()

{

   //string由c字符串衍生过来的

   string s1 = "craig david";

   string s2("7 days");

   string s3 = s2;

   string s4(10,'a');

   cout << s4 << endl;

   system("pause");

}

这个string,就是STL中义的,是不是跟JAVA很像了??

还包括了一些方法,如 string.length(); 

但这个string和C中的char* 还是不一样的!故是需要转换的!

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(); 这个方法,可以将string型转为char*型,前面要加一个常量,不然会报错

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开始查找"google"的位置

int idx = s1.find("google", 0);

cout << idx << endl;

//统计apple出现的次数

int idx_app = s1.find("apple",0);

//npos大于任何有效下标的值

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');

//只能删除一个字符

s1.erase(it);

//开头末尾插入字符串

s1.insert(0, "macos");

s1.insert(s1.length(), " facebook");

cout << s1 << endl;

system("pause");

}

//大小写转换

void main()

{

   string s1 = "JASON";

   //原始字符串的起始地址,原始字符串的结束地址, 目标字符串的起始地址, 函数名称

   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");

}

你可能感兴趣的:(C++ STL标准库 string)