温馨提示×

C++中strrchr的使用示例有哪些

c++
小樊
84
2024-08-15 11:03:39
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

  1. 找到字符串中最后一个特定字符的位置:
#include <iostream>
#include <cstring>

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 << "' is at position " << lastOccurrence - str << std::endl;
    } else {
        std::cout << "Character '" << ch << "' not found in the string." << std::endl;
    }
    
    return 0;
}
  1. 找到文件路径中文件名的位置:
#include <iostream>
#include <cstring>

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 + 1 << std::endl; // +1 to exclude the backslash
    } else {
        std::cout << "File name not found in the path." << std::endl;
    }
    
    return 0;
}

这些示例展示了如何在C++中使用strrchr函数来查找字符串中最后一个特定字符的位置。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何在C++中优化strrchr的使用

0