上一篇我们已经完成了 string 类的构造、拷贝、赋值与基本容量操作,这一篇继续把剩下的成员函数和全局函数补齐:resize、find、substr、关系运算符,以及流输入输出 operator<<、operator>> 和 getline。
resize
resize 是调整字符串大小的函数,假设调整为 n。
如果 n <= _size,则直接将 _str[n] 处置为 \0 进行截断,然后让 _size = n。
如果 n > _size,若不指定字符 ch,则默认 ch 为 \0,通过填充字符 ch 来达到长度 n。
在调整前还需判断是否需要扩容。
cpp
void string::resize(size_t n, char ch)
{
if (n > _capacity)
reserve(n);
if (n > _size)
{
for (size_t i = _size;i < n;i++)
{
_str[i] = ch;
}
_str[n] = '\0';
_size = n;
}
else
{
_str[n] = '\0';
_size = n;
}
}
可以看到,无论 n <= _size 还是 n > _size,最后都要把 _str[n] 置为 \0 并更新 _size = n,所以这两步可以提到 if 外面合并执行,代码更简洁:
cpp
void string::resize(size_t n, char ch)
{
if (n > _capacity)
reserve(n);
if (n > _size)
{
for (size_t i = _size; i < n; i++)
{
_str[i] = ch;
}
}
_str[n] = '\0';
_size = n;
}
这样两种分支共用同一段收尾逻辑,既避免了重复代码,也保证了 _str 始终以 \0 结尾、_size 与实际长度一致。
测试一下:
cpp
string s1("123456");
cout << s1.c_str() << endl;
s1.resize(2);
cout << s1.c_str() << endl;
s1.resize(5, 'x');
cout << s1.c_str() << endl;

find 和 substr
find 我们实现两个版本:一个是从指定 pos 位置开始查找字符 c,另一个是从指定 pos 位置开始查找字符串 str。
cpp
size_t find(const char c, size_t pos = 0);
size_t find(const char* str, size_t pos = 0);
从 pos 位置开始查找前,要先确保 pos 位置的有效性;找到即返回该字符第一次出现位置的下标,找不到则返回 npos。
cpp
size_t string::find(const char c, size_t pos)
{
assert(pos < _size);
while (pos < _size)
{
if (_str[pos] == c)
return pos;
pos++;
}
return npos;
第二个版本是查找子串,这里可以复用 strstr 去查找:strstr 返回 NULL 则说明没有找到,函数返回 npos;找到则返回对应下标位置。
cpp
size_t string::find(const char* str, size_t pos)
{
assert(pos < _size);
char* ptr = strstr(_str + pos, str);
if (ptr == NULL)
return npos;
else
return ptr - _str;
}
substr 函数是从 pos 位置开始,返回长度为 len 的子串对象。
首先我们要确保 pos 位置的有效性。
如果 len > _size - pos,则将 len 置为 _size - pos,然后以 pos 位置开始、长度为 len 的字符串内容去构造一个对象 tmp,并将该对象返回。
cpp
string string::substr(size_t pos, size_t len)
{
assert(pos < _size);
if (len > _size - pos)
len = _size - pos;
string tmp;
tmp.reserve(len);
while (len-- > 0)
{
tmp += _str[pos++];
}
tmp += '\0';
return tmp;
}
测试一下:
cpp
string s2 = "https://legacy.cplusplus.com/reference/";
size_t pos = s2.find(':');
if (pos != string::npos)
cout << s2.substr(0, pos).c_str() << endl;
size_t old = pos + 3;
pos = s2.find('/', old);
if (pos != string::npos)
cout << s2.substr(old, pos - old).c_str() << endl;

函数功能没什么问题。
relational operators
一些 string 对象的关系运算符重载,我们实现其中两个,剩下的复用就好了。
cpp
bool string::operator>(const string& s)
{
size_t i1 = 0, i2 = 0;
while (i1 < _size && i2 < s._size)
{
if (_str[i1] > s._str[i2])
return true;
else if (_str[i1] < s._str[i2])
return false;
i1++;
i2++;
}
return i1 != _size;
}
bool string::operator==(const string& s)
{
size_t i1 = 0, i2 = 0;
while (i1 < _size && i2 < s._size)
{
if (_str[i1] != s._str[i2])
return false;
i1++;
i2++;
}
return i1 == _size && i2 == s._size;
}
bool string::operator>=(const string& s)
{
return *this > s || *this == s;
}
bool string::operator<(const string& s)
{
return !(*this >= s);
}
bool string::operator<=(const string& s)
{
return !(*this > s);
}
bool string::operator!=(const string& s)
{
return !(*this == s);
}
测试一下:
cpp
string s1("hello world");
string s2("hello worldabc");
string s3("hello");
string s4("abcdef");
cout << (s1 == s2) << endl;
cout << (s1 > s2) << endl;
cout << (s1 > s3) << endl;
cout << (s1 < s4) << endl;
cout << (s1 < s3) << endl;
cout << (s1 != s4) << endl;

结果符合预期,代码功能正常。
operator<<
输出字符串内容,如果字符串内容为 "hello \0world",我们直接输出 _str,那么遇到 \0 输出就会停止,导致输出内容不全。
所以我们要一个个字符去输出,需要写一个循环。
cpp
std::ostream& operator<<(std::ostream& out, const string& s)
{
for (size_t i = 0;i < s._size;i++)
{
out << s._str[i];
}
return out;
}
测试一下:
cpp
string s1("hello");
s1 += '\0';
s1 += "world";
cout << s1 << endl;

operator>>
在给一个 string 对象 s 输入字符串内容时,要先把s中原有的内容清空(clear()),然后再输入内容。
我们并不知道要输入多少内容,所以一个字符一个字符去写入。
我们定义一个字符 ch,先写入一个字符,然后进入循环,判断 ch 是否是 ' ' 或 '\n',如果是则停止写入,不是则写入该字符,继续输入字符到 ch。
cpp
std::istream& operator>>(std::istream& in, string& s)
{
s.clear();
char ch;
in >> ch;
while (ch != ' ' && ch != '\n')
{
s += ch;
in >> ch;
}
s += '\0';
return in;
}
测试一下:
cpp
string s1("hello");
cin >> s1;
cout << s1 << endl;

我们发现 s1 读取遇到 ' ' 和 '\n' 也没有停止,显然出了问题。
调试时发现,ch 读完第一行的内容,跳转到了 d,和预期的 '\n' 不符。
这是因为 cin 默认以 ' ' 和 '\n' 为分隔符,在读取时会自动忽略这两个,导致读取一直无法结束。
所以我们应该直接去输入流中获取字符,C++中是有这个函数的,叫get()。

所以应该写成ch = in.gret(),而不是in >> ch。
而且如果我们输入很长的字符串的话,每次都要尾插,这样效率就会变低。
我们可以定义一个buff数组,长度为100,将读取到的输入字符放入该数组中,用index去遍历该数组。
当index == 99时,说明放满了,将buff[index] = '\0', s+=buff ,i = 0;,开启下一轮保存。
或者当ch == ' ' || ch == '\n'时,退出读取操作,此时若index != 0,则说明buff数组中还有内容需要输入到字符串,buff[index] = '\0',s += buff。
cpp
std::istream& operator>>(std::istream& in, string& s)
{
s.clear();
char buff[100];
int index = 0;
char ch = in.get();
while (ch != ' ' && ch != '\n')
{
buff[index++] = ch;
if (index == 99)
{
buff[index] = '\0';
s += buff;
index = 0;
}
ch=in.get();
}
if (index)
{
buff[index] = '\0';
s += buff;
}
return in;
}
我们测试一下:

功能没什么问题。
getline
当我们需要手动更改读取时的分隔符时,就需要用到 getline 函数,它的实现逻辑和 operator>> 几乎一样,只是循环条件变为了 ch != delim。
cpp
std::istream& getline(std::istream& in, string& s, const char delim)
{
s.clear();
char buff[100];
int index = 0;
char ch = in.get();
while (ch != delim)
{
buff[index++] = ch;
if (index == 99)
{
buff[index] = '\0';
s += buff;
index = 0;
}
ch = in.get();
}
if (index)
{
buff[index] = '\0';
s += buff;
}
return in;
}
测试一下:
cpp
string s1("hello");
getline(cin, s1, 'l');
cout << s1 << endl;

函数功能正常。
至此,string 的模拟实现就完成了。