栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

string&c

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

string&c

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

#include 
#include 

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 
#include 
#include 

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/690316.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号