string 找find

这段代码展示了在C++中如何使用fopen函数打开并写入文件,同时提取文件名的扩展名。通过对字符串的rfind和substr方法的运用,可以方便地获取文件扩展名。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
void A() {
    string file("test.txt.zip");
    FILE* fout = fopen(file.c_str(), "w");
    size_t pos = file.rfind('.');
    if (pos != string::npos)//npos=-1的意思{
        //string suf = file.substr(pos, file.size() - pos);
        string suf = file.substr(pos);
        cout << suf << endl;
    }
};
void B() {
    A();
}
int main() {
    B();
    return 0;
}

### C++ 中 `std::string` 的 `find` 方法不到时的返回值 在 C++ 标准库中,`std::string` 类提供了多种用于查子串的方法,其中最常用的就是 `find` 方法。如果通过 `find` 方法未能到目标子串,则会返回一个特殊的值 `std::string::npos`[^1]。 #### 关于 `std::string::npos` `std::string::npos` 是一个静态常量成员变量,其值是一个非常大的整数值(通常是 `-1` 转换为无符号整数后的结果)。它表示未到匹配项的结果。因此,在实际编程过程中,可以通过比较 `find` 方法的返回值与 `std::string::npos` 来判断是否到了目标子串: ```cpp #include <iostream> #include <string> int main() { std::string str = "csdn"; if (str.find("-") == std::string::npos) { std::cout << "Not Found\n"; } else { std::cout << "Found\n"; } return 0; } ``` 上述代码展示了如何检测 `"-"` 是否存在于字符串 `"csdn"` 中。由于 `"-"` 并不存在于该字符串中,程序将输出 `"Not Found"`。 #### 查成功时的行为 当调用 `find` 方法并成功定位到子串时,方法将返回第一个匹配项的起始索引位置(从零开始计数)。例如: ```cpp #include <iostream> #include <string> int main() { std::string str = "aabc"; int pos = str.find("abc"); if (pos != std::string::npos) { std::cout << pos << std::endl; // 输出结果是 1 } else { std::cout << "not find!\n"; } return 0; } ``` 在此示例中,子串 `"abc"` 存在于字符串 `"aabc"` 中,并且它的起始位置是从第 1 个字符开始计算得出的索引值 `1`[^2]。 #### 反向查功能 除了常规的正向查外,C++ 还支持反向查操作。可以利用 `rfind` 方法实现这一需求。此方法的作用是从右至左扫描源字符串中的指定模式,并返回最后一次出现的位置;如果没有发现任何匹配情况,则依旧返回 `std::string::npos`[^4]。 以下是使用 `rfind` 方法的一个简单实例: ```cpp #include <iostream> #include <string> int main() { std::string s = "example example"; std::string flag = "example"; size_t position = s.rfind(flag); if(position != std::string::npos){ std::printf("s.rfind(flag): %zu\n", position); } return 0; } ``` 这段代码片段演示了如何寻单词 `"example"` 在字符串 `"example example"` 中最后一次出现的位置。假如两者之间存在差异,则表明目标子串并非独一无二地存在于母串之中。 --- ### 总结 综上所述,对于无法查到的目标子串而言,无论是采用哪种形式的查方式——包括但不限于普通的 `find()` 或者逆序版的 `rfind()` ——只要最终没有命中预期的内容,它们都将统一给出相同的回应信号即 `std::string::npos` 值作为反馈依据[^1][^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值