C++ 中的 strchr() 函式及其應用
在本文中,我們將討論 C++ STL 中 strchr() 函式的工作原理、語法和示例。
什麼是 strchr()?
strchr() 函式是 C++ STL 中的一個內建函式,它在 <cstring> 標頭檔案中被定義。strchr() 函式用於查詢字元在字串中首次出現的位置。此函式返回一個指向字串中字元首次出現位置的指標。
如果字串中不存在該字元,函式將返回空指標。
語法
char* strchr( char* str, char charac );
引數
該函式接收以下引數:
str -這是我們要在其中查詢字元的字串。
charac -這是我們要在字串 str 中搜索的字元。
返回值
此函式返回一個指向字串中字元首次出現位置的指標。如果找不到字元,則返回空指標。
輸入 -
char str[] = "Tutorials Point"; char ch = ‘u’;
輸出 - 字元 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP