C++11 原始字符串字面量:轻松处理多行与特殊字符

C++11 引入了原始字符串字面量(raw string literals),这使得在字符串中包含特殊字符(如换行符、引号等)变得更加方便,而无需进行转义。原始字符串字面量以 R 开头,后面可以跟一对圆括号括起来的分隔符,这对分隔符用于标识字符串的起始和结束,并且可以自定义。

图片[1]_C++11 原始字符串字面量:轻松处理多行与特殊字符_知途无界

语法

原始字符串字面量的基本语法是:

R"delimiter(raw_characters)delimiter"
R"delimiter(raw_characters)delimiter"
R"delimiter(raw_characters)delimiter"
  • R:表示这是一个原始字符串字面量。
  • delimiter:可选的分隔符,可以是由字母、数字、下划线等组成的任意序列(包括空序列),用于避免字符串内容中的字符与结束标记冲突。
  • raw_characters:字符串的实际内容,不需要对特殊字符进行转义。

示例

  1. 基本用法
#include <iostream>
int main() {
std::string rawStr = R"(This is a raw string with "quotes" and \ backslashes.)";
std::cout << rawStr << std::endl;
return 0;
}
#include <iostream>

int main() {
    std::string rawStr = R"(This is a raw string with "quotes" and \ backslashes.)";
    std::cout << rawStr << std::endl;
    return 0;
}
#include <iostream> int main() { std::string rawStr = R"(This is a raw string with "quotes" and \ backslashes.)"; std::cout << rawStr << std::endl; return 0; }
  1. 输出:
This is a raw string with "quotes" and \ backslashes.
This is a raw string with "quotes" and \ backslashes.
This is a raw string with "quotes" and \ backslashes.
  1. 自定义分隔符:如果字符串本身包含 ) 字符,可以使用自定义分隔符来避免冲突:
#include <iostream>
int main() {
std::string rawStr = R"custom(This raw string contains ) and other characters.)custom";
std::cout << rawStr << std::endl;
return 0;
}
#include <iostream>

int main() {
    std::string rawStr = R"custom(This raw string contains ) and other characters.)custom";
    std::cout << rawStr << std::endl;
    return 0;
}
#include <iostream> int main() { std::string rawStr = R"custom(This raw string contains ) and other characters.)custom"; std::cout << rawStr << std::endl; return 0; }
  1. 输出:
This raw string contains ) and other characters.
This raw string contains ) and other characters.
This raw string contains ) and other characters.
  1. 多行字符串:原始字符串字面量特别适合用于表示多行字符串:
#include <iostream>
int main() {
std::string multiLineStr = R"(This is a
multi-line
raw string.)";
std::cout << multiLineStr << std::endl;
return 0;
}
#include <iostream>

int main() {
    std::string multiLineStr = R"(This is a
    multi-line
    raw string.)";
    std::cout << multiLineStr << std::endl;
    return 0;
}
#include <iostream> int main() { std::string multiLineStr = R"(This is a multi-line raw string.)"; std::cout << multiLineStr << std::endl; return 0; }
  1. 输出:
This is a
multi-line
raw string.
This is a
multi-line
raw string.
This is a multi-line raw string.

注意事项

  • 原始字符串字面量不能包含以 ) 紧跟自定义分隔符的序列(如果使用了自定义分隔符),除非该序列是字符串内容的一部分且被包含在自定义分隔符之间。
  • 原始字符串字面量不能以单个空格作为分隔符,因为语法上不允许。

原始字符串字面量为处理包含复杂字符的字符串提供了极大的便利,特别是在处理正则表达式、HTML、SQL 查询等多行或包含特殊字符的文本时。

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞59 分享
No gain without pain.
不付出,无回报
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容