Would there be any copy function available that allows a substring to std::string?
Example -
const char *c = "This is a test string message";
I want to copy substring "test" to std::string.
strcpy can be used to copy one string to another. Remember that C strings are character arrays. You must pass character array, or pointer to character array to this function where string will be copied.
Suppose str1 and str2 are two string objects, len is the length of substring. We want to copy string str1 into the string object str2 then the syntax would look like: str1. copy(str2,len);
You can use the c_str() method of the string class to get a const char* with the string contents.
You can use a std::string
iterator constructor to initialize it with a substring of a C string e.g.:
const char *sourceString = "Hello world!";
std::string testString(sourceString + 1, sourceString + 4);
You might want to use a std::string_view
(C++17 onwards) as an alternative to std::string
:
#include <iostream>
#include <string_view>
int main()
{
static const auto s{"This is a test string message"};
std::string_view v{s + 10, 4};
std::cout << v <<std::endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With