มีหลายวิธีแปลงตัวอักษรเดี่ยว (char) เป็นสตริง (string) ใน C++
ตัวอย่างโค้ด - 3 วิธี
#include <iostream>
#include <string>
#include <sstream>
int main() {
char c = 'm';
// วิธี 1: String Constructor
std::string s(1, c);
std::cout << "Using string constructor : " << s << '\n';
// วิธี 2: String Stream
std::string s2;
std::stringstream ss;
ss << c;
ss >> s2;
std::cout << "Using string stream : " << s2 << '\n';
// วิธี 3: push_back
std::string s3;
s3.push_back(c);
std::cout << "Using string push_back : " << s3 << std::endl;
return 0;
}
ผลลัพธ์
Using string constructor : m
Using string stream : m
Using string push_back : m
คำอธิบายแต่ละวิธี
- String Constructor:
std::string s(1, c);สร้างสตริงยาว 1 ตัวอักษรจาก char - String Stream: ใช้
stringstreamใส่ char แล้วดึงออกมาเป็น string - push_back:
s3.push_back(c);เพิ่ม char ต่อท้ายสตริงว่าง
วิธีแรก (Constructor) เป็นที่นิยมมากที่สุด เพราะกระชับและอ่านง่าย