1 标准库 std::string
c++ 中的 std::string 是一个重要的字符串的类, 我们在日常工作中常常与之打交道。
string是C++标准库的重要部分,主要用于字符串处理。使用string库需要在同文件中包括该库 #include<string>
std::string 实际上是 std::basic_string<char>:std::basic_string - cppreference.com
template<typename _CharT, typename _Traits = char_traits<_CharT>,
typename _Alloc = allocator<_CharT> >
class basic_string;
typedef basic_string<char> string;
代码示例:
#include<iostream>
#include<string>
int main()
{
std::string ss;
// Creating a string from const char*
std::string str1 = "hello";
char* c_str2 = "world!";
std::string str2(c_str2);
// Concatenating strings
std::string str3 = str1 + " " + str2;
// Print out the result
std::cout << str3 << '\n';
std::cout << str1 << ' ' << str2 << '\n';
// Accessing an element using subscript operator[]
std::cout << str1[0] << '\n';
str1[0] = 'W';
std::cout << str1 << '\n';
return 0;
}
输出:
2 自定义 String 代码
// mystring.h
class String
{
public:
String(char* data = nullptr);
~String();
// copy constructor
String(const String& str);
// copy assignment
String& operator=(const String& str);
// move constructor
String(String&& str);
// move assignmend
String& operator=(String&& str);
char* get_c_str() const;
private:
char* m_data;
};
// mystring.cpp
#include "mystring.h"
#include <stdio.h>
#include<string.h>
String::String(char* data)
{
if(data)
{
m_data = new char[strlen(data) + 1];
strcpy(m_data, data);
m_data[strlen(data)] = '\0';
}
else
{
m_data = new char[1];
m_data[0] = '\0';
}
}
String::~String()
{
delete [] m_data;
}
String::String(const String& str)
{
m_data = new char[strlen(str.m_data) + 1];
strcpy(m_data, str.m_data);
m_data[strlen(str.m_data)] = '\0';
}
String& String::operator=(const String& str)
{
if(this == &str)
{
return *this;
}
delete [] m_data;
m_data = new char[strlen(str.m_data) + 1];
strcpy(m_data, str.m_data);
return *this;
}
String::String(String&& str):m_data(str.m_data)
{
str.m_data = nullptr;
}
String& String::operator=(String&& str)
{
m_data = str.m_data;
str.m_data = nullptr;
return *this;
}
char* String::get_c_str() const
{
return m_data;
}
// main.cpp
#include"mystring.h"
#include<iostream>
std::ostream& operator<<(std::ostream& os, const String& str)
{
//os << str.get_c_str();
os << str.get_c_str();
return os;
}
int main()
{
String s1("abcde");
std::cout << s1 << std::endl;
// copy constructor
String s2 = s1;
std::cout << s2 << std::endl;
String s3("s3");
s3 = s1; // copy assignment
std::cout << s3 << std::endl;
String s4(String("bbb")); // move constructor
std::cout << s4 << std::endl;
String s5 = String("sss5"); // move assignment
std::cout << s5 << std::endl;
return 0;
}
输出如下: