You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中找到指定字符并提取其前方内容?

实现提取邮箱中'.'前的内容到firstName变量

你的需求可以通过C++ string类的substr()方法实现,同时需要修正原代码里的类型问题,具体如下:

原代码的问题说明

  • double pos = email.find(dot);:string::find()返回的是string::size_type(无符号整数类型),用double存储会导致不必要的类型转换,甚至可能在某些场景下出错,应该替换为正确的类型。
  • 提取'.'之前的内容,直接使用substr(0, pos)即可,substr的第一个参数是起始索引,第二个参数是要提取的字符长度。

修正后的完整代码

#include <iostream>
#include <string>
using namespace std;

int main() {
    string email, firstName, lastName;
    char dot = '.';
    
    cout << "What is your email?" << endl;
    getline(cin, email);
    
    // 使用正确的类型存储find的结果
    string::size_type pos = email.find(dot);
    
    // 检查是否找到'.',避免越界
    if (pos != string::npos) {
        firstName = email.substr(0, pos);
    } else {
        // 如果没有找到'.',设置默认值并提示
        cout << "Email format does not contain a dot." << endl;
        firstName = "";
    }
    
    cout << firstName << endl;
    return 0;
}

关键逻辑解释

  • email.find(dot):查找邮箱字符串中第一个'.'的位置,返回其索引;如果未找到,返回string::npos。
  • email.substr(0, pos):从索引0开始,提取长度为pos的子串,也就是'.'之前的所有内容。
  • 增加了判断逻辑,处理输入的邮箱中没有'.'的情况,避免程序出现未定义行为。

内容的提问来源于stack exchange,提问作者confusedPro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:10:20