ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน strchr() ใน C++ STL
strchr() คืออะไร
ฟังก์ชัน strchr() เป็นฟังก์ชัน inbuilt ใน C++ STL ซึ่งกำหนดไว้ในไฟล์ส่วนหัว
หากไม่มีอักขระอยู่ในสตริง ฟังก์ชันจะส่งกลับตัวชี้ null
ไวยากรณ์
char* strchr( char* str, char charac );
พารามิเตอร์
ฟังก์ชันยอมรับพารามิเตอร์ต่อไปนี้-
-
str − เป็นสตริงที่เราต้องค้นหาตัวละคร
-
ลักษณะ − เป็นอักขระที่เราต้องการค้นหาในสตริง str.
คืนค่า
ฟังก์ชันนี้จะส่งกลับตัวชี้ไปยังตำแหน่งที่อักขระปรากฏขึ้นครั้งแรกในสตริง หากไม่พบอักขระจะส่งกลับตัวชี้ null
ป้อนข้อมูล −
char str[] = "Tutorials Point"; char ch = ‘u’;
ผลผลิต − คุณมีอยู่ในสตริง
ตัวอย่าง
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char str[] = "Tutorials Point";
char ch_1 = 'b', ch_2 = 'T';
if (strchr(str, ch_1) != NULL)
cout << ch_1 << " " << "is present in string" << endl;
else
cout << ch_1 << " " << "is not present in string" << endl;
if (strchr(str, ch_2) != NULL)
cout << ch_2 << " " << "is present in string" << endl;
else
cout << ch_2 << " " << "is not present in string" << endl;
return 0;
} ผลลัพธ์
b is not present in string T is present in string
ตัวอย่าง
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char str[] = "Tutorials Point";
char str_2[] = " is a learning portal";
char ch_1 = 'b', ch_2 = 'T';
if (strchr(str, ch_1) != NULL){
cout << ch_1 << " " << "is present in string" << endl;
}
else{
cout << ch_1 << " " << "is not present in string" << endl;
}
if (strchr(str, ch_2) != NULL){
cout << ch_2 << " " << "is present in string" << endl;
strcat(str, str_2);
cout<<"String after concatenation is : "<<str;
}
else{
cout << ch_2 <<" " << "is not present in string" << endl;
}
return 0;
} ผลลัพธ์
b is not present in string T is present in string String after concatenation is : Tutorials Point is a learning portal