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

Substring ใน C++ (std::string::substr)

Substring คือส่วนหนึ่งของ String ใช้ substr(pos, len) ของ std::string

รูปแบบ

string substr(size_t pos = 0, size_t len = npos) const;
  • pos − ตำแหน่งเริ่มต้น (0-based)
  • len − จำนวนตัวอักษร (Default: จนจบ String)

ตัวอย่างโค้ด

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Apples are red";
    string str2 = str1.substr(11, 3);  // ตำแหน่ง 11 ยาว 3
    string str3 = str1.substr(0, 6);   // ตำแหน่ง 0 ยาว 6
    
    cout << "Substring(11,3): " << str2 << endl;
    cout << "Substring(0,6): " << str3 << endl;
    return 0;
}

ผลลัพธ์

Substring(11,3): red
Substring(0,6): Apples

รายละเอียด

  • str1 = "Apples are red" (Index: 0=A, 1=p, ..., 6=space, 7=a, 8=r, 9=e, 10=space, 11=r, 12=e, 13=d)
  • substr(11,3) = "red" (Index 11,12,13)
  • substr(0,6) = "Apples" (Index 0-5)

Edge Cases

  • pos > size() → Throw std::out_of_range
  • len > size() - pos → Return จนจบ String
  • substr() (ไม่มี Argument) → Copy ทั้ง String

C-style String

ไม่มี substr() ต้องเขียนเองด้วย Pointer Arithmetic หรือ strncpy