theme: channing-cyan highlight: a11y-dark
小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
在 C++ 中,为了转义像“\n”这样的字符,我们使用一个额外的“\”。从 C++ 11 开始,我们可以使用未处理转义字符(如 \n \t 或 \” )的原始字符串。原始字符串的语法是文字以 R”( 开头,以 )” 结尾。
让我们看一个在 C++ 中查看原始字符串文字的示例:
// C++ 程序来演示原始字符串的工作。
#include <iostream>
using namespace std;
int main()
{
// A Normal string
string string1 = "juejin.\nFor.\njuejiners.\n" ;
// A Raw string
string string2 = R"(juejin.\nFor.\njuejiners.\n)";
cout << string1 << endl;
cout << string2 << endl;
return 0;
}
输出:
juejin.
For.
juejiners.
juejin.\nFor.\njuejiners.\n
在 C 和 C++ 中,字符串是一维字符数组,而 C 中的字符串数组是二维字符数组。声明它们的方法有很多,这里给出了一些有用的方法。
我们实际上通过创建一个指针数组来创建一个字符串文字数组。
C 和 C++ 都支持这一点。
#include <iostream>
int main()
{
const char *colour[4] = { "Blue", "Red",
"Orange", "Yellow" };
for (int i = 0; i < 4; i++)
std::cout << colour[i] << "\n";
return 0;
}
输出
Blue
Red
Orange
Yellow
当所有字符串的长度已知并且需要特定的内存占用时,此方法很有用。字符串的空间将在单个块中分配
这在 C 和 C++ 中都受支持。
#include <iostream>
int main()
{
// Initialize 2D array
char colour[4][10] = { "Blue", "Red", "Orange",
"Yellow" };
// Printing Strings stored in 2D array
for (int i = 0; i < 4; i++)
std::cout << colour[i] << "\n";
return 0;
}
输出
Blue
Red
Orange
Yellow
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有