I want to copy a set of characters from an array, from an index to another.
For example i have an array char array[64] and I want to select characters from let's say 5-15 and store them in another char array.
I could do that with a for loop, but is there any function that does that? Like the C# method Substring. Thanks in advance.
7 Answers
You can always use memcpy to achieve that and it would be more efficient anyway.
char a[100] = {0};
char b[100] = {1};
memcpy(&a[10], &b[30], 10);
6 Comments
std::copy_n be any better/different?std:copy_n would work with i.e. std::vector or std::string?C++: use std::copy_n:
#include <algorithm>
int main() {
char a[100] = {0};
char b[100] = {1};
std::copy_n(&a[10], 10, &b[30]);
}
Comments
There are several approaches. For example you can use standard C function strncpy. For example
strncpy( dest, source + 5, 11 );
Or you can use standard C++ algorithm std::copy. For example
std::copy( source + 5, source + 16, dest );
Or you can use standard algorithm `std::copy_n. For example
std::copy_n( source + 5, 11, dest );
But if you will use lambda expressions then the set of standard algorithms that can be used for this operation will be enlarged.:)
2 Comments
You've really asked two rather different questions, and (so far) most of the answers you've gotten have concentrated exclusively on one.
The one they've answered is how to copy characters in arrays.
At the end of your question, however, you say: "Like the C# method Substring."
That really points in an entirely different direction: at least in C++ (but not C) the closest equivalent of C#'s Substring is std::string's substr. For example:
std::string a("12345678");
std::string b = a.substr(2,3); // b == 345
std::string also supplies a number of constructors that let you create one string as a substring of another, so you could achieve the same effect with:
std::string b = std::string(a, 2, 3);
My immediate advice: if you're going to write C++, write real C++. Especially with the similarity in syntax, it's easy to think of C++ as C with a few extra bells and whistles.
In reality, well written C++ is generally quite different from well written C. In good C++, raw arrays, raw pointers, and functions like strncpy and memcpy are generally quite rare. One of the major strengths of C++ is supporting relatively high-level abstractions with little or no penalty in efficiency. I'd advise making use of that.
Comments
#include <string.h>
char array[64];
char new_array[12]; /* 12th char for '\0' */
/* put some data into array */
/* copy chars 5-15 (11 chars) from array to new_array */
strncpy(new_array, &array[4], 11);
std::copy? BTW these two-language questions are not very productive.strncpy()and/orstd::copy().