简体   繁体   中英

C++ std::string InputIterator code to C code

I have some C++ code that I found that does exactly what I need, however I need it in C and I do not know how I could do it in C, so I am hoping someone can help me out.

The C++ code is:

std::string value( (const char *)valueBegin, (const char *)valueEnd );

This is using the string::string constructor:

template<class InputIterator> string (InputIterator begin, InputIterator end);

Can anyone help me in converting this to C code?

Thanks!

// Get the number of characters in the range
size_t length = valueEnd - valueBegin;

// Allocate one more for the C style terminating 0
char *data = malloc(length + 1);

// Copy just the number of bytes requested
strncpy(data, valueBegin, length);

// Manually add the C terminating 0
data[length] = '\0';

The C++ code creates new string from substring of another string. Similiar functionality in C is strndup :

char *str = strndup(valueBegin, valueEnd - valueBegin);
// ...
free(str);

通过假定指针算法在您的情况下有意义:

strncpy( value, valueBegin, valueEnd-valueBegin );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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