【问题标题】:Remove special character and string after it inside char array在 char 数组中删除特殊字符和字符串
【发布时间】:2015-07-18 11:26:55
【问题描述】:

我有一封类型为 char 数组的电子邮件:

char email[80] = "pewdiepie@harvard.edu.au"

如何删除@ 和它后面的字符串并得到pewdiepie 作为最终结果?

【问题讨论】:

标签: c++ regex string char


【解决方案1】:

比如下面这种方式

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);

【讨论】:

    【解决方案2】:

    简单

    #include <string>
    
    std::string email("pewdiepie@harvard.edu.au");
    email.erase(email.find('@'));
    

    【讨论】:

      【解决方案3】:

      如果你坚持让它有一个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';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-21
        • 2021-04-23
        • 2011-04-11
        • 2016-01-23
        相关资源
        最近更新 更多