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

ฟังก์ชัน match_results::length() ใน C++ STL

ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน match_results::length() ใน C++ STL

match_results ใน C++ STL คืออะไร?

std::match_results เป็นคลาสคล้ายคอนเทนเนอร์เฉพาะทาง ที่ใช้เก็บคอลเลกชันของลำดับตัวอักษรที่จับคู่ได้ ในคลาสนี้ regex match operation หา matches ของ target sequence

match_results::length() คืออะไร?

ฟังก์ชัน match_results::length() เป็นฟังก์ชันในตัวของ C++ STL อยู่ใน header <regex> ใช้ตรวจสอบความยาวของ n-th match ใน match_results object

length() รับพารามิเตอร์เป็นหมายเลข match (ต้องน้อยกว่า match_results::size()) match number 0 แทน entire match expression

ไวยากรณ์

smatch_name.length(unsigned int num);

พารามิเตอร์

ฟังก์ชันรับพารามิเตอร์ 1 ตัว คือ match number (ต้องน้อยกว่า size ของคอนเทนเนอร์)

ค่าที่คืน

คืนค่า unsigned integer คือความยาวของ nth match

ตัวอย่าง

Input: std::smatch; smatch.length(0); Output: 0

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

#include <bits/stdc++.h>
using namespace std;

int main() {
    string str = "TutorialsPoint";
    regex R("(Tutorials)(.*)");
    smatch Mat;
    regex_match(str, Mat, R);
    for(int i = 0; i < Mat.size(); i++) {
        cout << "Match is : " << Mat[i] << endl;
    }
    return 0;
}

เอาต์พุต

Match is : TutorialsPoint
Match is : Tutorials
Match is : Point

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

#include <bits/stdc++.h>
using namespace std;

int main() {
    string sr = "Tutorials Point";
    regex Re("(Tutorials)(.*)");
    smatch Mat;
    regex_match(sr, Mat, Re);
    int len = 0;
    string str;
    for(int i = 1; i < Mat.size(); i++) {
        if(Mat.length(i) > len) {
            str = Mat[i];
            len = Mat.length(i);
        }
    }
    cout << "Match length is of: " << len;
    return 0;
}

เอาต์พุต

Match length is of: 9