Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Raw String Literal ใน C++: ใช้งานสตริงที่มี Escape Characters

Raw String Literal คืออะไร?

ใน C++ มี escape characters เช่น \n (newline), \t (tab), \\ (backslash), \" (quote) ถ้าต้องการพิมพ์ตัวอักษรเหล่านี้ **ตามตัวจริง** โดยไม่ให้ compiler แปลง ให้ใช้ **Raw String Literal**

Syntax

R"delimiter(raw_string)delimiter"
  • R - prefix บ่งบอก raw string
  • delimiter - ตัวคั่น optional (สูงสุด 16 ตัวอักษร) ใช้เมื่อ raw string มี ) หรือ " อยู่ในตัว
  • เนื้อหาระหว่าง ( และ ) จะถูกตีความ **ตามตัวอักษรจริง** ไม่มี escape sequence

ตัวอย่างพื้นฐาน

#include <iostream>
using namespace std;

int main() {
    string normal = "tutorials\npoint\n";
    string raw = R"(tutorials\npoint\n)";
    
    cout << "Normal: " << normal;      // แสดงจริง: ทับบรรทัด
    cout << "Raw: " << raw;            // แสดง: tutorials\npoint\n
    return 0;
}

Output

Normal: tutorials
point

Raw: tutorials\npoint\n

ตัวอย่างกับ Tab และ Quote

string normal = "tutorials\tpoint\t";
string raw = R"(tutorials\tpoint\t)";

cout << "Normal: " << normal; // tutorials    point    
cout << "Raw: " << raw;       // tutorials\tpoint\t

ใช้ Delimiter เมื่อมี ) หรือ " ในสตริง

// ผิด: R"(abc)"def)" // compiler หงุดหงิด
// ถูก:
string s1 = R"delim(abc)"def)delim";  // เนื้อหา: abc)"def
string s2 = R"xyz(hello)world)xyz";   // เนื้อหา: hello)world

ประโยชน์จริง

  • Regular Expressions: R"(\d{4}-\d{2}-\d{2})" แทน "\\d{4}-\\d{2}-\\d{2}"
  • File Paths (Windows): R"(C:\Users\Name\Documents)"
  • JSON/XML/HTML snippets
  • Multi-line strings

ตัวอย่าง Multi-line

string sql = R"(SELECT id, name
FROM users
WHERE age > 18
ORDER BY name;)";

cout << sql;

สรุป

Raw String Literal ทำให้โค้ดอ่านง่ายขึ้น ลดความผิดพลาดจาก double-escaping เหมาะสำหรับ regex, paths, และ multi-line text