ใน C++ strchr() เป็นฟังก์ชันที่กำหนดไว้ล่วงหน้า ใช้สำหรับการจัดการสตริง และส่งคืนตำแหน่งแรกที่พบของตัวอักษรที่กำหนดในสตริงที่ให้มา
ไวยากรณ์ของ strchr() มีดังนี้:
char *strchr( const char *str, int c)
จากไวยากรณ์ข้างต้น str คือสตริงที่มีตัวอักษร c ฟังก์ชัน strchr() จะหาตำแหน่งแรกของ c ใน str
โปรแกรมที่สาธิตฟังก์ชัน strchr() มีดังนี้:
ตัวอย่าง
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "strings";
char * c = strchr(str,'s');
cout << "First occurrence of character "<< *c <<" in the string is at position "<< c - str + 1;
return 0;
}ผลลัพธ์
First occurrence of character s in the string is at position 1
ในโปรแกรมนี้ เริ่มต้นด้วยการนิยามสตริง str จากนั้นพอยน์เตอร์ c ชี้ไปยังตำแหน่งแรกของตัวอักษร s ในสตริงที่กำหนด ได้จากการใช้ strchr() ตำแหน่งของ s ถูกแสดงด้วย cout โค้ดส่วนนี้มีดังนี้:
char str[] = "strings"; char * c = strchr(str,'s'); cout << "First occurrence of character "<< *c <<" in the string is at position "<< c - str + 1;
ฟังก์ชัน strchr() ยังสามารถใช้แสดงสตริงหลังจากตัวอักษรที่พบครั้งแรกได้ กล่าวคือ สามารถแสดง suffix ของสตริงได้ โปรแกรมสาธิตมีดังนี้:
ตัวอย่าง
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "strings";
char * c = strchr(str,'i');
cout << "Remaining string after first occurance of "<< *c <<" is "<< c ;
return 0;
}ผลลัพธ์
Remaining string after first occurance of i is ings
ในโปรแกรมนี้ เริ่มต้นด้วยการนิยามสตริง str จากนั้นพอยน์เตอร์ c ชี้ไปยังตำแหน่งแรกของตัวอักษร s ในสตริงที่กำหนด ได้จากการใช้ strchr() ส่วนที่เหลือของสตริงจากตำแหน่งที่ c ชี้ไปจะถูกพิมพ์ด้วย cout โค้ดส่วนนี้มีดังนี้:
char str[] = "strings"; char * c = strchr(str,'i'); cout << "Remaining string after first occurance of "<< *c <<" is "<< c ;