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