我在想是否有可能在 C++ 中创建一个包含数据的字符串,我不想创建一个字符串字符串或一个字符串数组。
假设我有一个字符串mv:
mv =
"hello
new
world "
Run Code Online (Sandbox Code Playgroud)
“你好”、“新”和“世界”在不同的行中。现在,如果我们打印mv,那么“hello”、“new”和“world”应该出现在不同的行上。
我也在考虑竞争性编程。如果我将查询的所有答案连接在一个字符串中,然后将答案或cout所有查询一一输出,那么这两个输出是否会有时间差?
我希望我的字符串变量以这种格式存储信息,因此像我的字符串变量 mv 应该在第一行有一些字符串,在第二行有一些字符串,这整个应该像单个字符串一样工作
C++ 中的字符串( std::string) 是什么?
它是一个可动态调整大小的字符数组的容器,配备了操作该数组的方法。
字符数组是:
characters: |c0|c1|c2|c3|...|cN|
Run Code Online (Sandbox Code Playgroud)
这就是一个的性质std::string。对此你无能为力。
什么是一行(文本)?
在 C++ 或任何其他编程语言中没有对行的正式定义。甲线是一个视觉概念属于读取和写入配置在2维空间的文本。一条线垂直高于或低于另一条线。
计算机不会在二维空间中排列数据。他们将这一切安排在线性、一维、存储中。没有数据垂直高于或低于任何其他数据。
但是当然编程语言可以表示文本行,并且它们都按照相同的约定来做。按照惯例,一行是一个以换行序列结尾的字符数组。
一个新的线序是本身的一个或两个字符数组,这取决于您的操作系统的约定。Windows 使用 2 个字符的序列
carriage-return,line-feed。类 Unix 操作系统使用 1 个字符的序列line-feed。您可以在Wikipedia: Newline 中研究该主题
。但是为了可移植性,在 C++ 源代码中,换行序列 - 无论它实际上是什么 - 由转义序列
表示\n,您可以在源代码中将其用作字符。
所以字符数组:
|h|e|l|l|o|\n|
Run Code Online (Sandbox Code Playgroud)
表示文本行:
hello
Run Code Online (Sandbox Code Playgroud)
在 C++ 中。和字符数组:
|h|e|l|l|o|\n|n|e|w|\n|w|o|r|l|d|\n|
Run Code Online (Sandbox Code Playgroud)
表示三行文本:
hello
new
world
Run Code Online (Sandbox Code Playgroud)
如果您想将该数组存储在单个 中std::string,C++ 允许您这样做:
std::string s0{'h','e','l','l','o','\n','n','e','w','\n','w','o','r','l','d','\n'};
Run Code Online (Sandbox Code Playgroud)
或更方便的是:
std::string s1{"hello\nnew\nworld\n"};
Run Code Online (Sandbox Code Playgroud)
甚至 - 如果您对使用\n转义序列有恐惧症- 像这样:
std::string s2
{R"(hello
new
world
)"};
Run Code Online (Sandbox Code Playgroud)
所有这些在字符串中存储三行的方法都会在该字符串中创建完全相同的字符数组,即:
|h|e|l|l|o|\n|n|e|w|\n|w|o|r|l|d|\n|
Run Code Online (Sandbox Code Playgroud)
它们都创建完全相同的std::string.
如果您打印这些字符串中的任何一个,您将看到相同的内容,例如这个程序:
#include <string>
#include <iostream>
int main() {
std::string s0{'h','e','l','l','o','\n','n','e','w','\n','w','o','r','l','d','\n'};
std::string s1{"hello\nnew\nworld\n"};
std::string s2 // Yes...
{R"(hello
new
world
)"}; // ...it is meant to be formatted like this
std::cout << "--------------" << std::endl;
std::cout << s0;
std::cout << "--------------" << std::endl;
std::cout << s1;
std::cout << "--------------" << std::endl;
std::cout << s2;
std::cout << "--------------" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
--------------
hello
new
world
--------------
hello
new
world
--------------
hello
new
world
--------------
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32266 次 |
| 最近记录: |