简体   繁体   English

将char数组中的元素范围提取到字符串中

[英]Extract range of elements from char array into string

I want to extract a range of elements from the beginning of a char array and put them into a string. 我想从char数组的开头提取一系列元素并将它们放入一个字符串中。 The range may be less than or equal to the number of elements. 范围可以小于或等于元素的数量。

This is what I have come up with. 这就是我想出的。

// buffer is a std::array<char, 128>

std::string message;

for (int i = 0; i < numberToExtract; ++i)
{
    message += buffer.at(i);
}

Is there a better way to do this? 有一个更好的方法吗?

I've been looking at something like std::string's iterator constructor. 我一直在寻找像std :: string的迭代器构造函数。 Eg std::string(buffer.begin(), buffer.end()) but I don't want all the elements. 例如std::string(buffer.begin(), buffer.end())但我不想要所有的元素。

Thanks. 谢谢。

You don't have to go all the way to end : 你不必一直走到end

std::string(buffer.begin(), buffer.begin() + numberToExtract)

or: 要么:

std::string(&buffer[0], &buffer[numberToExtract]);

or use the constructor that takes a pointer and a length: 或者使用带有指针和长度的构造函数:

std::string(&buffer[0], numberToExtract);
std::string(buffer.data(), numberToExtract);

You're close with your second example, you can do 你接近你的第二个例子,你可以做到

std::string(buffer.begin(), buffer.begin() + numberToExtract)

This is using pointer arithmetic since array's use contiguous memory. 这是使用指针算法,因为数组使用连续的内存。

随机访问迭代器允许您进行算术运算:

std::string(buffer.begin(), buffer.begin() + numberToExtract);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM