C++ 如何将 const char * 转换为 std::string

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8126498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:03:02  来源:igfitidea点击:

How to convert a const char * to std::string

c++

提问by Allan

What is the correct/best/simplest way to convert a c-style string to a std::string.

将 c 样式字符串转换为 std::string 的正确/最佳/最简单方法是什么。

The conversion should accept a max_length, and terminate the string at the first \0 char, if this occur before max_length charter.

转换应该接受 max_length,并在第一个 \0 字符处终止字符串,如果这发生在 max_length 宪章之前。

采纳答案by Vlad

This page on string::stringgives two potential constructors that would do what you want:

此页面上string::string提供了两个潜在的构造函数,它们可以执行您想要的操作:

string ( const char * s, size_t n );
string ( const string& str, size_t pos, size_t n = npos );

Example:

例子:

#include<cstdlib>
#include<cstring>
#include<string>
#include<iostream>
using namespace std;

int main(){

    char* p= (char*)calloc(30, sizeof(char));
    strcpy(p, "Hello world");

    string s(p, 15);
    cout << s.size() << ":[" << s << "]" << endl;
    string t(p, 0, 15);
    cout << t.size() << ":[" << t << "]" << endl;

    free(p);
    return 0;
}

Output:

输出:

15:[Hello world]
11:[Hello world]

The first form considers pto be a simple array, and so will create (in our case) a string of length 15, which however prints as a 11-character null-terminated string with cout << .... Probably not what you're looking for.

第一种形式被认为p是一个简单的数组,因此将创建(在我们的例子中)一个长度为 15 的字符串,但是它打印为一个 11 个字符的以空字符结尾的字符串cout << ...。可能不是你要找的。

The second form will implicitly convert the char*to a string, and then keep the maximum between its length and the nyou specify. I think this is the simplest solution, in terms of what you have to write.

第二种形式将隐式转换char*为字符串,然后保持其长度和n您指定的最大值之间的最大值。我认为这是最简单的解决方案,就您必须编写的内容而言。

回答by ephemient

std::string str(c_str, strnlen(c_str, max_length));


At Christian Rau's request:

Christian Rau的要求:

strnlenis specified in POSIX.1-2008and available in GNU's glibcand the Microsoft run-time library. It is not yet found in some other systems; you may fall back to Gnulib's substitute.

strnlenPOSIX.1-2008中指定并在 GNU 的glibcMicrosoft 运行时库中可用。在其他一些系统中尚未发现;你可能会回到Gnulib的替代品。

回答by Dani

std::string the_string(c_string);
if(the_string.size() > max_length)
    the_string.resize(max_length);

回答by James Kanze

This is actually trickier than it looks, because you can't call strlenunlessthe string is actually nul terminated. In fact, without some additional constraints, the problem practically requires inventing a new function, a version of strlenwhich never goes beyond the a certain length. However:

这实际上比看起来更棘手,因为strlen除非字符串实际上以 nul 结尾,否则您无法调用。事实上,如果没有一些额外的约束,这个问题实际上需要发明一个新函数,它的版本strlen永远不会超过一定的长度。然而:

If the buffer containing the c-style string is guaranteed to be at least max_lengthchar's (although perhaps with a '\0'before the end), then you can use the address-length constructor of std::string, and trim afterwards:

如果保证包含 c 样式字符串的缓冲区至少是 max_length字符(尽管可能'\0'在结尾之前带有 a ),那么您可以使用 , 的地址长度构造函数std::string,然后进行修剪:

std::string result( c_string, max_length );
result.erase( std::find( result.begin(), result.end(), '
std::string result( c_string, std::min( strlen( c_string ), max_length ) );
' ), result.end() );

and if you know that c_stringis a nul terminated string (but perhaps longer than max_length, you can use strlen:

如果您知道这c_string是一个以 nul 结尾的字符串(但可能长于max_length,您可以使用strlen

 std::string cppstr(cstr, cstr + min(max_length, strlen(cstr)));

回答by 6502

There is a constructor accepting two pointer parameters, so the code is simply

有一个构造函数接受两个指针参数,所以代码很简单

const char *c_style = "012abd";
std::string cpp_style = new std::string(c_style, 0, 10);

this is also going to be as efficient as std::string cppstr(cstr)if the length is smaller than max_length.

这也将std::string cppstr(cstr)与长度小于max_length.

回答by kbyrd

What you want is this constructor: std::string ( const string& str, size_t pos, size_t n = npos ), passing pos as 0. Your const char* c-style string will get implicitly cast to const string for the first parameter.

您想要的是这个构造函数: std::string ( const string& str, size_t pos, size_t n = npos ),将 pos 作为 0 传递。您的 const char* c 样式字符串将隐式转换为第一个参数的 const 字符串。

##代码##