如何在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
相关产品推荐
相关产品推荐

