【问题标题】:How to get substring from char pointer in C++? [closed]如何从 C++ 中的 char 指针获取子字符串? [关闭]
【发布时间】:2017-10-29 00:11:28
【问题描述】:

我想从 char 指针中获取子字符串,在第 1 行打印成功,但如果是第 2 行则不成功。但是在 cout 打印中是这样的。

为什么?我该如何纠正?

char* substring(const char* src, int start_index, int end_index){ // src - source
  int length = end_index - start_index;
  char *dest; // destination
  if (length < 0) {
    return NULL;
  } else {
      dest = (char*)malloc(sizeof (char)* (length + 1));
      dest[length] = '\0';
      memcpy(dest, src + start_index, length);
      return dest;
  }
}
int main() {
  //char *p = "phab"; // line 1
  char *p = substring("alphabet",2, 6); // line 2
  cout << p << endl;
  if (p == "phab") cout << "ok\n";
}

【问题讨论】:

  • 你在混合 C 和 C++ 吗?
  • 最后一行不好,你比较两个地址。如果要比较字符串,请使用 strcmp( )
  • @SouravGhosh:您不能在同一源代码中混合使用 C 和 C++。这是 C++,不是 C。
  • 我错过了什么?
  • 指针不是字符串,因此它没有“子字符串”。如果需要字符串,请使用字符串类。

标签: c++ pointers malloc substring memcpy


【解决方案1】:

您的代码的主要问题是尝试将字符串与p == "phab" 进行比较。

这不比较字符串,它比较它们在内存中的位置。要比较字符串,请使用std::strcmp

我对您的代码做了一些注释/建议。

char* substring(const char* src, int start_index, int end_index) {

    int length = end_index - start_index;

    if (length < 0)
        return NULL;

    char* dest = new char[length + 1]; // use new[] not malloc

    std::copy(src + start_index, src + end_index, dest); // prefer to memcopy
    dest[length] = '\0';

    return dest;
}

int main() {
  //char *p = "phab"; // line 1
  char* p = substring("alphabet", 2, 6); // line 2

  cout << p << endl;

  // use strcmp()
  if (std::strcmp(p, "phab") == 0) cout << "ok\n";

  delete[] p; // don't forget to delete your memory
}

【讨论】:

  • 感谢您的支持
【解决方案2】:

您可以通过多种不同的方式来做到这一点。

打印子字符串

如果您只想将char * 的子字符串打印到cout,请使用write()

const char *str = alphabet;
int start_index = 2, end_index = 6;
std::cout.write(str + start_index, end_index - start_index);

构造一个 std::string

如果你想构造一个std::string

const char *str = alphabet;
int start_index = 2, end_index = 6;
std::string substr{str + start_index, end_index - start_index};
std::string substr{str + start_index, str + end_index}; // equivalent
std::cout << substr;
const char *substr_ptr = substr.c_str(); // watch out for lifetime

比较

如果要比较,if (p == "phab") 会比较p 是否包含与"phab" 的地址相同的地址。答案是“否”,因为p 是由malloc() 创建的。您可以使用std::strcmp() 比较char * 字符串。

if (std::strcmp(p, "phab") == 0) {
    cout << "ok\n";
}

否则,substring() 函数可以正常工作,尽管它不是惯用的 C++ 并且不进行任何错误检查。请记住,std::malloc 可以返回 NULL。大多数人不在 C++ 中使用 malloc 是有原因的。

【讨论】:

  • 也感谢您的支持
猜你喜欢
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 2019-09-07
  • 1970-01-01
  • 2015-05-19
  • 2010-12-12
  • 2020-05-29
  • 1970-01-01
相关资源
最近更新 更多