将 char* 转换为字符串 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8438686/
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
Convert char* to string C++
提问by Terry Li
I know the starting address of the string(e.g., char* buf
) and the max length int l;
of the string(i.e., total number of characters is less than or equal to l
).
我知道字符串的起始地址(例如char* buf
)和字符串的最大长度int l;
(即字符总数小于或等于l
)。
What is the simplest way to get the value of the string
from the specified memory segment? In other words, how to implement string retrieveString(char* buf, int l);
.
string
从指定的内存段获取值的最简单方法是什么?换句话说,如何实现string retrieveString(char* buf, int l);
.
EDIT: The memory is reserved for writing and reading string of variable length. In other words, int l;
indicates the size of the memory and not the length of the string.
编辑:内存保留用于写入和读取可变长度的字符串。换句话说,int l;
表示内存的大小而不是字符串的长度。
采纳答案by Benjamin Lindley
std::string str(buffer, buffer + length);
Or, if the string already exists:
或者,如果字符串已经存在:
str.assign(buffer, buffer + length);
Edit:I'm still not completely sure I understand the question. But if it's something like what JoshG is suggesting, that you want up to length
characters, or until a null terminator, whichever comes first, then you can use this:
编辑:我仍然不完全确定我理解这个问题。但是,如果它类似于 JoshG 的建议,您需要最多length
字符或直到空终止符(以先到者为准),那么您可以使用以下命令:
std::string str(buffer, std::find(buffer, buffer + length, 'char *charPtr = "test string";
cout << charPtr << endl;
string str = charPtr;
cout << str << endl;
'));
回答by Taha
basic_string(const charT* s,size_type n, const Allocator& a = Allocator());
回答by chill
Use the string's constructor
使用字符串的构造函数
basic_string(const charT* s, const Allocator& a = Allocator());
EDIT:
编辑:
OK, then if the C string length is not given explicitly, use the ctor:
好的,那么如果没有明确给出 C 字符串长度,则使用 ctor:
string retrieveString( char* buf, int max ) {
size_t len = 0;
while( (len < max) && (buf[ len ] != 'std::string str;
char* const s = "test";
str.assign(s);
') ) {
len++;
}
return string( buf, len );
}
回答by Amish Programmer
There seems to be a few details left out of your explanation, but I will do my best...
你的解释似乎有一些细节遗漏,但我会尽力......
If these are NUL-terminated strings or the memory is pre-zeroed, you can just iterate down the length of the memory segment until you hit a NUL (0) character or the maximum length (whichever comes first). Use the string constructor, passing the buffer and the size determined in the previous step.
如果这些是 NUL 终止的字符串或内存已预置零,您可以向下迭代内存段的长度,直到遇到 NUL (0) 字符或最大长度(以先到者为准)。使用字符串构造函数,传递缓冲区和上一步中确定的大小。
##代码##If the above is not the case, I'm not sure how you determine where a string ends.
如果上述情况并非如此,我不确定您如何确定字符串的结束位置。