将任何字符串转换为固定大小的字符串

Convert any string to fixed size string

本文关键字:字符串 任何 转换      更新时间:2023-10-16

我在下面的代码中使用set_effect_block将字符串转换为20字节的固定长度字符串。

class editoritems{
  public:
    editoritems(string= "");
    void set_effect_block(string paramnamestring)          //set effect block
    { 
      const char *effectnamevalue=paramnamestring.data();  
      int length=strlen(effectnamevalue);
      length=(length<20?length:19);
      strncpy_s(effe_block,effectnamevalue,length);
      effe_block[length]='';
    }
    string get_effect_block()const{return effe_block;}
  private:
    char effe_block[20];
};
editoritems::editoritems(string h)
{
  set_effect_block(h);
}

这是一个好方法吗?有更快的方法吗?

试试这个:

void set_effect_block(string paramnamestring)
{
    size_t copied = paramnamestring.copy(effe_block, 19);
    effe_block[copied] = '';
}

BTW:你可能想要考虑使用const std::string& paramnamestring作为editoritems::set_effect_block()的参数,这样字符串就不需要被复制到函数中。

相关文章: