我有一个类型为char array的电子邮件:
char email[80] = "pewdiepie@harvard.edu.au"
如何删除@
后面的字符串并将pewdiepie
作为最终结果?
答案 0 :(得分:4)
例如以下方式
if ( char *p = std::strchr( email, '@' ) ) *p = '\0';
在C语言中,您必须在if语句之前声明变量p
。例如
char *p;
if ( ( p = strchr( email, '@' ) ) != NULL ) *p = '\0';
如果使用类型为std::string
的对象而不是字符数组,那么
std::string email( "pewdiepie@harvard.edu.au" );
然后你可以写
auto pos = email.find( '@' );
if ( pos != std::string::npos ) email.erase(pos);
答案 1 :(得分:1)
简单地
#include <string>
std::string email("pewdiepie@harvard.edu.au");
email.erase(email.find('@'));
答案 2 :(得分:0)
如果你坚持让它保持char [],而不是字符串
char email[80] = "pewdiepie@harvard.edu.au";
char name[80]; // to hold the new string
name[std::find(email, email + 80, '@') - email] = '\0'; // put '\0' in correct place
strncpy(name, email, std::find(email, email + 80, '@') - email); // copy the string
如果你想改变原来的char [],
*(std::find(email, email + 80, '@')) = '\0';