将char *转换为字符串C ++ [英] Convert char* to string C++
问题描述
我知道字符串的起始地址(例如, char * buf
)和最大长度 int l;
的字符串(即,字符总数小于或等于 l
)。
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
).
什么是最简单的方法是从指定的内存段中获取 string
的值?换句话说,如何实现 string retrieveString(char * buf,int 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);
.
EDIT :该存储器保留用于写入和读取可变长度的字符串。换句话说, 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.
推荐答案
std::string str(buf, buf + l);
或者,如果字符串已存在:
Or, if the string already exists:
str.assign(buf, buf + l);
修改:我仍然不能完全确定我理解这个问题。但是如果它像JoshG建议的那样,你想要 l
个字符,或者直到一个空终止符,以先到为准,那么你可以使用这个:
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 l
characters, or until a null terminator, whichever comes first, then you can use this:
std::string str(buf, std::find(buf, buf + l, '\0'));
这篇关于将char *转换为字符串C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!