strchr 和 strstr 是 C++ 中兩個常用的字符串處理函數,它們的主要區別在于它們的用途和功能
strchr 函數用于在一個字符串中查找第一次出現某個特定字符的位置。它接受兩個參數:一個字符串(源字符串)和一個要查找的字符。如果找到了該字符,strchr 返回一個指向該字符在字符串中首次出現位置的指針;否則,返回 NULL。例如:
#include <iostream>
#include <cstring>
int main() {
const char* str = "Hello, World!";
char ch = 'W';
char* result = strchr(str, ch);
if (result != NULL) {
std::cout << "The character '" << ch << "' is found at position: " << result - str << std::endl;
} else {
std::cout << "The character '" << ch << "' is not found in the string." << std::endl;
}
return 0;
}
strstr 函數用于在一個字符串中查找第一次出現某個子字符串的位置。它接受兩個參數:一個源字符串和一個子字符串。如果找到了該子字符串,strstr 返回一個指向子字符串在源字符串中首次出現位置的指針;否則,返回 NULL。例如:
#include <iostream>
#include <cstring>
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_str << "' is found at position: " << result - str << std::endl;
} else {
std::cout << "The substring '" << sub_str << "' is not found in the string." << std::endl;
}
return 0;
}
總結一下,strchr 用于查找一個字符在字符串中的位置,而 strstr 用于查找一個子字符串在源字符串中的位置。這兩個函數都返回指向找到的字符或子字符串的指針,如果沒有找到則返回 NULL。