如何将char *指针转换为C ++字符串? [英] How to convert a char* pointer into a C++ string?

查看:290
本文介绍了如何将char *指针转换为C ++字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++ 字符串。我需要传递这个字符串到接受 char * 参数的函数(例如 - strchr())。

I have a C++ string. I need to pass this string to a function accepting a char* parameter (for example - strchr()).

a)如何获取指针?

a) How do I get that pointer?

b)是否有一些等同于 strschr()的函数适用于 C ++字符串?

b) Is there some function equivalent to strschr() that works for C++ strings?

推荐答案


  1. string等价于
    C ++ string object use c_str
    函数。

  2. 要在字符串中找到
    char code> object use
    find_first_of 函数。

  1. To get the C string equivalent of the C++ string object use c_str function.
  2. To locate the first occurence of a char in a string object use find_first_of function.

示例:

string s = "abc";

// call to strlen expects char *
cout<<strlen(s.c_str());  // prints 3

// on failure find_first_of return string::npos
if(s.find_first_of('a') != string::npos)
    cout<<s<<" has an a"<<endl;
else
    cout<<s<<" has no a"<<endl;

注意:我给了 strlen 使用 char * 的函数示例。

Note: I gave the strlen just an example of a function that takes char*.

这篇关于如何将char *指针转换为C ++字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆