Devdit
 

String array C/C++ สร้างตัวแปร Array ชนิด String

1.1K

String array C สร้างตัวแปร Array ชนิด String บทความนี้สอนวิธีสร้างตัวแปรเก็บข้อความ หรือ String แบบ Array โดยตัวอย่างสร้างเป็น Array 2 มิติรองรับการเก็บ String มากกว่า 1 ข้อมูล สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง String array C/C++ สร้างตัวแปร Array ชนิด String

/* ภาษา C */
#include <stdio.h>

int main() {
    char colors[3][10] = {
      "red",
      "green",
      "blur"
    };
    
    printf("%s\n%s\n%s", colors[0], colors[1], colors[2]);
    return 0;
}
/* ภาษา C++ */
#include <iostream>
using namespace std;

int main() {
    char colors[3][10] = {
      "red",
      "green",
      "blur"
    };  
    std::cout << colors[0] << endl;
    std::cout << colors[1] << endl;
    std::cout << colors[2] << endl;
    return 0;
}

ผลลัพธ์

red
green
blur

คำอธิบาย

String array C/C++ สร้างตัวแปร Array ชนิด String จากตัวอย่าง คือตัวแปรชื่อ colors ชนิด char แบบ array เก็บค่า string หรือข้อความ เวลาต้องการเข้าถึงข้อมูลสามารถเข้าถึงผ่านลำดับ (index) ของ array ได้เลย เช่น 0 = red, 1 = green และ 2 = blue

แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ