阅读量:91
strchr 和 strstr 是 C++ 中两个常用的字符串处理函数,它们的主要区别在于它们的用途和功能
- strchr:
strchr函数用于在一个字符串中查找第一次出现某个特定字符的位置。它接受两个参数:一个字符串(源字符串)和一个要查找的字符。如果找到了该字符,strchr返回一个指向该字符在字符串中首次出现位置的指针;否则,返回 NULL。
例如:
#include
#include
int main() {
const char* str = "Hello, World!";
char ch = 'W';
char* result = strchr(str, ch);
if (result != NULL) {
std::cout << "The character '" << ch class="hljs-string">"' is found at position: " << result class="hljs-keyword">else {
std::cout << "The character '" << ch class="hljs-string">"' is not found in the string." << std class="hljs-keyword">return 0;
}
- strstr:
strstr函数用于在一个字符串中查找第一次出现某个子字符串的位置。它接受两个参数:一个源字符串和一个子字符串。如果找到了该子字符串,strstr返回一个指向子字符串在源字符串中首次出现位置的指针;否则,返回 NULL。
例如:
#include
#include
int main() {
const char* str = "Hello, World!";
const char* sub_str = "World";
char* result = strstr(str, sub_str);
if (result != NULL) {
std::cout << "The substring '" << sub class="hljs-string">"' is found at position: " << result class="hljs-keyword">else {
std::cout << "The substring '" << sub class="hljs-string">"' is not found in the string." << std class="hljs-keyword">return 0;
}
总结一下,strchr 用于查找一个字符在字符串中的位置,而 strstr 用于查找一个子字符串在源字符串中的位置。这两个函数都返回指向找到的字符或子字符串的指针,如果没有找到则返回 NULL。