阅读量:131
- 找到字符串中最后一个特定字符的位置:
#include
#include
int main() {
const char* str = "Hello, world!";
char ch = 'o';
const char* lastOccurrence = strrchr(str, ch);
if (lastOccurrence != NULL) {
std::cout << "Last occurrence of '" << ch class="hljs-string">"' is at position " << lastOccurrence class="hljs-keyword">else {
std::cout << "Character '" << ch class="hljs-string">"' not found in the string." << std class="hljs-keyword">return 0;
}
- 找到文件路径中文件名的位置:
#include
#include
int main() {
const char* filePath = "C:\\Users\\user\\Documents\\file.txt";
const char* fileName = strrchr(filePath, '\\');
if (fileName != NULL) {
std::cout << "File name is: " << fileName class="hljs-number">1 << std class="hljs-comment">// +1 to exclude the backslash
} else {
std::cout << "File name not found in the path." << std class="hljs-keyword">return 0;
}
这些示例展示了如何在C++中使用strrchr函数来查找字符串中最后一个特定字符的位置。