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

การนับจำนวนตัวอักษรและคำใน String ด้วย PL/SQL

PL/SQL: นับตัวอักษรและคำในข้อความ

ใช้ลูป FOR วนอ่านแต่ละตัวอักษร นับตัวอักษรทั้งหมด และนับคำจากช่องว่าง

ตัวอย่าง: "Tutorials Point"

DECLARE
    str VARCHAR2(40) := 'Tutorials Point';
    nchars NUMBER(4) := 0;
    nwords NUMBER(4) := 1; -- เริ่มที่ 1 เพราะคำแรกไม่มี space นำหน้า
    s CHAR;
BEGIN
    FOR i IN 1..LENGTH(str) LOOP
        s := SUBSTR(str, i, 1);
        nchars := nchars + 1;
        IF s = ' ' THEN
            nwords := nwords + 1;
        END IF;
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('count of characters is: ' || nchars);
    DBMS_OUTPUT.PUT_LINE('Count of words are: ' || nwords);
END;

ผลลัพธ์

count of characters is: 15
Count of words are: 2

คำอธิบาย: "Tutorials Point" มี 14 ตัวอักษร + 1 ช่องว่าง = 15 ตัวอักษร, 2 คำ

ตัวอย่างเพิ่มเติม: "Honesty is the best policy" → 26 ตัวอักษร (24 + 4 spaces), 5 คำ

ข้อควรพิจารณา: วิธีนี้นับคำจากช่องว่าง (Space) เท่านั้น หากมี Tab, Newline, หรือ Space หลายช่องติดกัน อาจนับไม่ถูกต้อง ควรใช้ REGEXP ใน PL/SQL ที่ทันสมัยกว่า