当前位置:实例文章 » JAVA Web实例» [文章]第一百一十六天学习记录:C++提高:STL-string(黑马教学视频)

第一百一十六天学习记录:C++提高:STL-string(黑马教学视频)

发布人:shili8 发布时间:2025-03-03 21:50 阅读次数:0

**第一百一十六天学习记录**

**C++提高:STL-string(黑马教学视频)**

今天是学习的第116天,我决定继续深入地学习C++中的STL(string)。黑马教学视频提供了非常详细的讲解和实例代码,帮助我更好地理解这些概念。

###1. string类概述string类是STL中用于表示字符串的类,它继承自basic_string类。string类提供了一系列的成员函数来操作字符串,如查找、替换、插入等。

####1.1 构造函数和赋值运算符

cpp// 构造函数template 
basic_string::basic_string(size_type n, InputIterator first, InputIterator last)
 : _M_dataplus(new alloc_type[n]), _M_len(n) {
 assign(first, last);
}

// 赋值运算符template 
basic_string& basic_string::operator=(const basic_string& str) {
 if (this != &str) {
 _M_dataplus = str._M_dataplus;
 _M_len = str._M_len;
 }
 return *this;
}


####1.2 查找函数
cpp// find函数template 
size_type basic_string::find(const charT* s, size_type pos) const {
 if (pos > _M_len)
 return string_npos;
 const charT* p = _M_dataplus + pos;
 while (*p && *s == *p) {
 ++s;
 ++p;
 }
 return *s ? pos : string_npos;
}

// rfind函数template 
size_type basic_string::rfind(const charT* s, size_type pos =0) const {
 if (pos > _M_len)
 return string_npos;
 const charT* p = _M_dataplus + _M_len -1;
 while (*p && *s == *p) {
 --s;
 --p;
 }
 return *s ? pos : string_npos;
}


####1.3 替换函数
cpp// replace函数template 
basic_string& basic_string::replace(size_type i, size_type j,
 const charT* str) {
 if (i > _M_len || j > _M_len)
 return *this;
 if (j - i == str_len(str)) {
 assign(_M_dataplus + i, str);
 _M_len += str_len(str) - (j - i);
 } else {
 basic_string tmp = *this;
 tmp.assign(_M_dataplus + j, str);
 assign(_M_dataplus + i, tmp.begin(), tmp.end());
 _M_len += str_len(str) - (j - i);
 }
 return *this;
}


####1.4 插入函数
cpp// insert函数template 
basic_string& basic_string::insert(size_type pos,
 const charT* s) {
 if (pos > _M_len)
 return *this;
 size_type len = str_len(s);
 assign(_M_dataplus + pos, s);
 _M_len += len;
 return *this;
}


###2. string类的使用
cppint main() {
 // 构造函数 std::string str1(5, 'a');
 std::cout << "str1: " << str1 << std::endl;

 // 赋值运算符 std::string str2 = "Hello";
 str2 = "World";
 std::cout << "str2: " << str2 << std::endl;

 // find函数 std::string str3("Hello World");
 size_t pos = str3.find("World");
 if (pos != std::string::npos) {
 std::cout << "Found 'World' at position " << pos << std::endl;
 }

 // rfind函数 pos = str3.rfind("World");
 if (pos != std::string::npos) {
 std::cout << "Found 'World' at position " << pos << std::endl;
 }

 // replace函数 str3.replace(6,5, "C++");
 std::cout << "str3: " << str3 << std::endl;

 // insert函数 str3.insert(7, "Programming ");
 std::cout << "str3: " << str3 << std::endl;

 return0;
}


以上是对string类的基本操作函数和使用示例的介绍。通过这些函数和实例,可以更好地理解string类的使用和应用。

### 总结本文主要讲解了C++中的STL(string)类及其相关函数的使用,包括构造函数、赋值运算符、查找函数、替换函数和插入函数。通过这些函数和实例,可以更好地理解string类的使用和应用。

### 后记本文是对黑马教学视频中关于STL(string)类的讲解和实例代码的总结和扩展。希望通过这篇文章,能够帮助读者更好地理解C++中的STL(string)类及其相关函数的使用和应用。

其他信息

其他资源

Top