这个轮子已经被发明出来,并且存在于标准库中。
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string word;
std::cout << "Enter a word: ";
std::cin >> word;
std::reverse(word.begin(), word.end());
std::cout << "Reverse: " << word << std::endl;
return 0;
}
要准确了解这里发生了什么,您必须首先介绍一些内容:
我希望你已经知道什么是类。如果您仍然处于介绍性内容,类基本上是用户定义的状态和行为集合。作者可以出于多种原因选择限制对类的状态或行为的访问。在std::string
标准库字符串类的情况下,所有状态都是隐藏的,只有行为是可访问的。
字符串类是一个包含字符的容器。还有许多其他容器类,每个类都有不同的优点和缺点。string 类包含具有严格顺序的字符序列。存在其他容器,例如std::set
、std::vector
、std::list
等。 std::string
与 有相似之处std::vector
,是 的远房表亲std::list
。每个集合的行为不同,适用于不同的事物。
您可能认为您需要了解 string 类如何存储其数据以便反转它,但您不需要。这就是迭代器的用武之地。std::string
拥有一个 typedef, std::string::iterator
,它是一个特殊的对象,用于存储字符串中单个元素的位置。 std::reverse
是一个库函数,它需要 2 个迭代器并反复交换它们的内容并将它们相互移动。这看起来像这样:
v v <-- positions of iterators (start at the start, end at the end)
ABC <-- initial state
v v <-- the end iterator moved back
ABC
v v
CBA <-- the iterators swapped their values
vv <-- the begin iterator moved forward
CBA
V <-- the end iterator moved back; both iterators are in the same place
CBA <-- therefore, we're done, the string is reversed
关于迭代器的一件事是它们有点像指针。事实上,您可以将指针传递给一些需要迭代器的函数,因为它们在语法上的行为相同。因此,您应该能够编写自己的反向函数,该函数使用的指针基本上与此相同,但使用char *
s 除外。
这里有一些伪代码,你应该可以用它来编写函数(我不会完全写出来,因为它是家庭作业):
namespace BaidNation
{
void reverse(char *begin, char *end)
{
loop forever
{
if (end equals begin):
done;
move end backwards;
if (end equals begin):
done;
swap end's and begin's characters;
move begin forwards;
}
}
}
请记住,BaidNation::reverse
(以及std::reverse
)期望end 是在集合结束之后引用元素的迭代器,而不是引用最后一个元素的迭代器。那么使用它有什么意义呢?
您的LengthOfString
函数返回字符串中非空字符的数量。由于数组是零索引的,我们知道,与任何其他数组一样,如果我们检查string1 + LengthOfString(string1)
,我们将获得一个指向末尾字符的指针,这一次正是我们想要的。
因此,我们可以使用它来反转字符串:
BaidNation::reverse(string1, string1 + LengthOfString(string1));
如果您必须更早地使用签名,您可以将此设计改编为另一种:
int reverse(const char str[])
{
char *start = str, *end = str + LengthOfString(str);
BaidNation::reverse(start, end);
}