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
广告