string&c_str()的使用

C语言中对字符串(char*)操作的方法较少,在c++ 中可将(char*)转换为string类进行操作。c++中可使用的c_str() 方法将string转换为const char *。 但使用该方法要注意使用场合,如使用不当,极易出现各种问题。

#include <iostream>
#include <string>

using namespace std;

const char *GetName(const char *nameAndID) {
  if (nameAndID == nullptr) {
    return nullptr;
  }
  std::string tmpStr = std::string(nameAndID);
  int pos = tmpStr.find("|");
  return tmpStr.substr(0, pos).c_str();
}

const char *GetID(const char *nameAndID) {
  if (nameAndID == nullptr) {
    return nullptr;
  }
  std::string tmpStr = std::string(nameAndID);
  int pos = tmpStr.find(";");
  return tmpStr.substr(pos + 1).c_str();
}

int main() {
    const char *str = "idealcitier|23333";
    std::string name = GetName(str);
    std::string ID = GetID(str);
    cout << name << endl;
    cout << ID << endl;
}

g++ 编译后,执行该代码,会出现随机结果,与预期idealcitier 23333不符。

出现上述结果的原因

  • std::string(nameAndID) 会创建string实例,创建在栈上
  • 在函数结束时,在栈上的资源会被回收,创建的string实例也就会被回收掉
  • 最终tmpStr.substr(0, pos).c_str() 返回的const char* 类型也会被回收掉,所以就出现了乱码的问题

所以要避免,返回string.c_str()作为函数的返回值。可直接返回string对象,避免资源的回收

#include <iostream>
#include <cstdint>
#include <string>

using namespace std;

std::string GetName(const char *nameAndID) {
  if (nameAndID == nullptr) {
    return nullptr;
  }
  std::string tmpStr = std::string(nameAndID);
  int pos = tmpStr.find("|");
  return tmpStr.substr(0, pos);
}

std::string GetID(const char *nameAndID) {
  if (nameAndID == nullptr) {
    return nullptr;
  }
  std::string tmpStr = std::string(nameAndID);
  int pos = tmpStr.find("|");
  return tmpStr.substr(pos + 1);
}

int main() {
    const char *str = "idealcitier|23333";
    std::string name = GetName(str);
    std::string ID = GetID(str);
    cout << name << endl;
    cout << ID << endl;
}

参考

[1] https://www.coder.work/article/34041

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值