Catalog
STL之string

c++ vector的用法

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void test01() {
string s;
s.assign("abcde", 4); //assign赋值进行截取个前
cout << s << endl;
char *p = (char*) "hello world";
s.assign(p, 10);
cout << s << endl;
s.assign(s, 2, 5); //从第二个开始截取5个数。
cout << s << endl;
//s = s.substr(2,5); //从第几个开始截取几个数 和assign一样
//cout << s;
}


void test02() {
string s = "hello world";
for (int i = 0; i < s.size(); ++i)
cout << s.at(i) << " ";
try {
cout << s.at(100);//可以触发异常,不会报错,但是貌似没啥大用
}
catch (out_of_range &e) {
cout << "异常为" << e.what();
}
catch (...) {
cout << "捕获到其他异常";
}
}

void test03() {
string s = "我";
string s2 = "爱北京天安门";
s.append(s2); //相当于 +=
cout << s << endl;
//find查找
string s3 = "abcdefg";
int pos = s3.find("bc");
cout << pos << endl;
pos = s3.find("bcf");
cout << pos << endl;
pos = s3.find("bc", 2);//可加参数,不加默认是0;
cout << pos << endl;
string s4 = "12345656";
//int find(const char *s, int pos, int n) const;//从pos开始查找字符串s中前n个字符在当前串中的位置
int pos2 = s4.rfind("56",s4.size()-1 -2,1);//从pos开始从后向前
cout << pos2 << endl;
//替换
string s5 = "hello";
s5.replace(1, 3, "1111");//从1开始的连续三个字符被替换成1111
cout << s5;

}


void test04() {
//(1)int compare(const basic_string& __str)
//和str按字典序比较大小,若小于str返回小于0的值,若等于str返回0,若大于str返回大于0的值
string a = "e";
string b = "H";
cout << a.compare(b);
string s = "aZ";
string s2 = "ab";
cout << s.compare(s2);



//(2)int compare(size_type __pos, size_type __n, const basic_string& __str)
//从pos位置开始长度为n的子字符串和str按字典序比较大小,返回值同上
s = "helloworld";
s2 = "rle";
cout << s.compare(7, 3, s2);

//(3)int compare(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2)
//从pos1位置开始长度为n1的子字符串和str从pos2位置开始长度为n2的子字符串按字典序比较大小,返回值同上
cout << s.compare(7, 3, s2, 0, 3);


}

void test05() {
string s1 ="37987244@qq.com";
string s2 = s1.substr(0, s1.find("@"));
cout << s2;
}

void test06() {
string s1 = "hello";
s1.insert(1, "111");
cout << s1 << endl;
s1.erase(1, 3);
cout << s1 << endl;
}

void func(string p) {
cout << p << endl;
}

void test07() {
string s = "abc";
char t[8] = "helloo";
cout << t << endl;
char *p = (char*)s.c_str();//c_str()生成一个const char*的指针
cout << p<< endl;
//func(s);//string 不能隐式转化为char *
func(p);//char * 可以隐式转化为string
string s2 = p;
cout << s2;

}
void test08() {
string s = "hello";
char &a = s[2];
char &b = s[3];
a = '1';
b = '2';
cout << s << endl << (char*)s.c_str();
s = "ppppp";
cout << a << " " << b;//此时可以继续使用a,b;
//s = "ppppppppppppppppppppp" 此时无法使用,因为编译器重新分配了一块内存;
}
int main()
{
test08();
}
Author: superzhaoyang
Link: http://yoursite.com/2020/03/28/STL之string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付宝

Comment