自学内容网 自学内容网

string类(c++)

一、概述

sting类是c++标准库的一个重要部分,主要用于字符串处理。在c语言中,字符串是以“\0”结尾的一些字符的集合,为了方便操作,c标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP(面向对象)的思想,而且底层空间需要用户自己管理,稍不留神哈可能会越界访问。

二、auto和范围for

 为了方便学习string类,先了解c++11中的auto和范围for

1、auto

  1. auto可以作为一个新的类新指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而得。
  2. 用auto声明指针类型实时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&
  3. 当在同一行声明多个变量时,这些变量必须是相同的类型,否则会编译报错,因为编译器实际上只对第一个类型进行推导,再用推导出来的类型定义其他变量
  4. auto不能作为函数的参数,但可以做返回值
  5. auto不能直接用来声明数组
#include<iostream>
using namespace std;
int func1()
{
  return 10;
}
// 不能做参数
void func2(auto a)
{  }

// 可以做返回值,但是建议谨慎使用
auto func3()
{
  return 3;
}
int main()
{
  int a = 10;
  auto b = a;
  auto c = 'a';
  auto d = func1();
  // 编译报错:rror C3531: “e”: 类型包含“auto”的符号必须具有初始值设定项
  auto e;
  int x = 10;
  auto y = &x;
  auto* z = &x;
  auto& m = x;

  auto aa = 1, bb = 2;
  // 编译报错:error C3538: 在声明符列表中,“auto”必须始终推导为同一类型
  auto cc = 3, dd = 4.0;
  // 编译报错:error C3318: “auto []”: 数组不能具有其中包含“auto”的元素类型
  auto array[] = { 4, 5, 6 };
  return 0;
}

2、范围for

  1.  对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此C++11中引入了基于范围的for循环。for循环后的括号由冒号:”分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的范围,自动迭代,自动取数据,自动判断结束。
  2. 范围for可以作用到数组和容器对象上进行遍历
  3. 范围for的底层很简单,容器遍历实际就是替换为迭代器
int main()
{
  int arr[] = {1, 2, 3, 4, 5};

  //范围for
  for(auto& e : arr)
  {
     e*=2; 
  {

  for(auto e : arr)
  {
    cout << e <<" " << endl
  }
  return 0;
}

三、string类常用的接口

1、string类对象的常见构造

void Teststring()
{
  string s1; // 构造空的string类对象s1
  string s2("hello bit"); // 用C格式字符串构造string类对象s2
  string s3(s2); // 拷贝构造s3
}

 2、string类对象的容量操作

 用法如下:

void Teststring1()
{
// 注意:string类对象支持直接用cin和cout进行输入和输出
string s("hello, bit!!!");
cout << s.size() << endl;
cout << s.length() << endl;
cout << s.capacity() << endl;
cout << s << endl;

// 将s中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
s.clear();
cout << s.size() << endl;
cout << s.capacity() << endl;

// 将s中有效字符个数增加到10个,多出位置用'a'进行填充
// “aaaaaaaaaa”
s.resize(10, 'a');
cout << s.size() << endl;
cout << s.capacity() << endl;

// 将s中有效字符个数增加到15个,多出位置用缺省值'\0'进行填充
// "aaaaaaaaaa\0\0\0\0\0"
// 注意此时s中有效字符个数已经增加到15个
s.resize(15);
cout << s.size() << endl;
cout << s.capacity() << endl;
cout << s << endl;

// 将s中有效字符个数缩小到5个
s.resize(5);
cout << s.size() << endl;
cout << s.capacity() << endl;
cout << s << endl;
}

注意:

1、size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()

2、clear()只是将对象中的有效字符清空,不改变底层空间大小。

3、resize(size_t n) resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不

     同的是当字符个数增多时: resize(n) 0 来填充多出的元素空间, resize(size_t n, char
     c) 用字符 c 来填充多出的元素空间。注意: resize 在改变元素个数时,如果是将元素个数
     增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。 
4、 reserve(size_t res_arg=0) :为 string 预留空间,不改变有效元素个数,当 reserve 的参
     数小于 string 的底层空间总大小时, reserver 不会改变容量大小。

 3、string类对象的访问及遍历操作

void Teststring3()
{
string s1("hello Bit");
const string s2("Hello Bit");
cout << s1 << " " << s2 << endl;
cout << s1[0] << " " << s2[0] << endl;

s1[0] = 'H';
cout << s1 << endl;

// s2[0] = 'h';   代码编译失败,因为const类型对象不能修改
}

void Teststring4()
{
string s("hello Bit");
// 3种遍历方式:
// 需要注意的以下三种方式除了遍历string对象,还可以遍历是修改string中的字符,
// 另外以下三种方式对于string而言,第一种使用最多
// 1. for+operator[]
for (size_t i = 0; i < s.size(); ++i)
cout << s[i] << endl;

// 2.迭代器
string::iterator it = s.begin();
while (it != s.end())
{
cout << *it << endl;
++it;
}

// string::reverse_iterator rit = s.rbegin();
// C++11之后,直接使用auto定义迭代器,让编译器推到迭代器的类型
auto rit = s.rbegin();
while (rit != s.rend())
cout << *rit << endl;

// 3.范围for
for (auto ch : s)
cout << ch << endl;
}

4、string类对操作对象的修改

void Teststring5()
{
string str;
str.push_back(' ');   // 在str后插入空格
str.append("hello");  // 在str后追加一个字符"hello"
str += 'b';           // 在str后追加一个字符'b'   
str += "it";          // 在str后追加一个字符串"it"
cout << str << endl;
cout << str.c_str() << endl;   // 以C语言的方式打印字符串

// 获取file的后缀
string file("string.cpp");
size_t pos = file.rfind('.');
string suffix(file.substr(pos, file.size() - pos));
cout << suffix << endl;

// npos是string里面的一个静态成员变量
// static const size_t npos = -1;

// 取出url中的域名
string url("http://www.cplusplus.com/reference/string/string/find/");
cout << url << endl;
size_t start = url.find("://");
if (start == string::npos)
{
cout << "invalid url" << endl;
return;
}
start += 3;
size_t finish = url.find('/', start);
string address = url.substr(start, finish - start);
cout << address << endl;

// 删除url的协议前缀
pos = url.find("://");
url.erase(0, pos + 3);
cout << url << endl;
}

注意:

1. 在string尾部追加字符时,s.push_back(c) / s.append(1, c) / s += 'c'三种的实现方式差不多,一般情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可 以连接字符串。

2. string 操作时,如果能够大概预估到放多少字符,可以先通过 reserve 把空间预留
好。
3.printf()函数不能直接打印string类的对象的内容,可以通过将string转换为char*类型,再使用printf()函数打印。

四、string类的模拟实现 

1、构造函数

string()
//为了和析构的delete适配所以加了[]
//不使用nullptr是为了实现c_str函数,
:_str(new char[1] {'\0'})
, _size(0)
,_capacity(0)
{

}

string(const char* str)
:_size(strlen(str))
,_capacity(_size)
,_str(new char[_size]+1)
{
strcpy(_str, str);
}

2、析构函数

~string()
{
delete[] _str;
_str = nullptr;
_size = 0;
_capacity = 0;
}

3、拷贝构造

string::string(const string& s)
{
_str = new char[_capacity + 1];
strcpy(_str,s._str);
_size = s._size;
_capacity = s._capacity;
}

4、=(赋值) 

string& string::operator=(const string& s)
{
delete[] _str;
_str = new char[s._capacity + 1];
strcpy(_str, s._str);
_size = s._size;
_capacity = s._capacity;
}

5、c_str

const char* c_str() const
{
return _str;
}

6、下标引用[ ]

char& operator[](size_t i)
{
assert(i < _size);
return _str[i];
}
const char& operator[](size_t i) const
{
assert(i < _size);
return _str[i];
}

7、迭代器

typedef char* iterator;
iterator begin()
{
return _str;
}
iterator end()
{
return _str + _size;
}
typedef const char* const_iterator;
const_iterator begin() const
{
return _str;
}
const_iterator end() const
{
return _str + _size;
}

注:范围for的底层就是迭代器,意味这支持迭代去就支持范围for

8、reserve(扩容)

void string::reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}

9、push_back(尾插字符)

void string::push_back(char ch)
{
//先检查空间
if (_size == _capacity) 
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
_str[_size] = ch;
_size++;
}

10、append(尾插字符串)

void string::append(const char* str)
{
size_t len= strlen(str);
if (_size + len > _capacity)
{
size_t newcapacity = 2 * _capacity;
//如果扩2倍不够,则需要多少括多少
if (newcapacity < _size + len)
{
newcapacity = _size + len;
}
reserve(newcapacity);
}
strcpy(_str + _size, str);
_size += len;
}

11、+=

string& string::operator+=(char ch)
{
push_back(ch);
}
string& string::operator+=(const char* str)
{
append(str);
}

12、insert(选择插入)

void string::insert(size_t pos,char ch)
{
if (_size == _capacity)//检查扩容
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
int end = _size;
while (end >= (int)pos)
{
_str[end + 1] = _str[end];
--end;
}
_str[pos] = ch;
_size++;
}
void string::insert(size_t pos, const char* str)
{
int len = strlen(str);
if (_size + len > _capacity)
{
size_t newcapacity = 2 * _capacity;
if (newcapacity < _size + len)
{
newcapacity = _size+len;
}
reserve(newcapacity);
}
int end = _size;
while (end >= (int)pos)
{
_str[end + len] = _str[end];
end--;
}

for (size_t i = 0; i < len; i++)
{
_str[pos + i] = str[i];
}
_size += len;
}

13、erase(清除数据)

void string::erase(size_t pos, size_t len)
{
if (len >= _size - pos)
{
_str[pos] = '\0';
_size = pos;
}
else
{
size_t end= pos + len;
while (end < _size)
{
_str[end - len] = _str[end];
++end;
}
_size -= len;
}
}

14、find(查找并返回下标)

size_t string::find(char ch, size_t pos)
{
for (size_t i = pos; i < _size; i++)
{
if (_str[i] ==ch)
{
return i;
}
}
return npos;
}


size_t string::find(const char* str, size_t pos)
{
const char* ptr = strstr(_str+pos, str);
if (ptr == nullptr)
{
return npos;
}
else
{
return ptr - _str;
}
}

15、substr(取子字符串)

string string::substr(size_t pos,size_t len)
{
//如果大于后面剩余的字符串的话,直接取到底
if (len > (_size - pos))
{
len = _size - pos;
}

my::string sub;
sub.reserve(len);
for (size_t i = 0; i < len; i++)
{
sub += _str[pos + i];
}

return sub;
}

16、比较

c++库里面把比较类的运算符重载实现成全局的,是为了解决字符串类型和string类型比较的问题

==

bool operator==(const string& lhs, const string& rhs)
{
return strcmp(lhs.c_str(), rhs.c_str()) == 0;
}

!=

bool operator!=(const string& lhs, const string& rhs)
{
return !(lhs == rhs);
}

>

bool operator>(const string& lhs, const string& rhs)
{
return !(lhs <= rhs);
}

<

bool operator<(const string& lhs, const string& rhs)
{
return strcmp(lhs.c_str(), rhs.c_str()) < 0;
}

>=

bool operator>=(const string& lhs, const string& rhs)
{
return !(lhs < rhs);
}

<=

bool operator<=(const string& lhs, const string& rhs)
{
return (lhs > rhs)||(lhs == rhs);
}

17、输入流,输出流,getline

   ostream& operator<<(ostream& os, const string& str)
{
for (size_t i = 0; i < str.size(); i++)
{
os << str[i];
}
return os;
}

istream& operator>>(istream& is, string& str)
{
str.clear();

int i = 0;
char buff[256];//缓冲区
char ch;
ch = is.get();
while (ch != ' ' && ch != '\n')
{
buff[i++] = ch;
if (i == 255)
{
buff[i] = '\0';
str += buff;
i = 0;
}
ch = is.get();
}

if (i > 0)
{
buff[i] = '\0';
str += buff;
}
return is;
}


istream& getline(istream& is, string& str, char delim )
{
str.clear();

int i = 0;
char buff[256];//缓冲区
char ch;
ch = is.get();
while (ch != '\n')
{
buff[i++] = ch;
if (i == 255)
{
buff[i] = '\0';
str += buff;
i = 0;
}
ch = is.get();
}

if (i > 0)
{
buff[i] = '\0';
str += buff;
}
return is;
}


原文地址:https://blog.csdn.net/qq_75271671/article/details/142989501

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!