开发者

Copy a substring from const char* to std::string

开发者 https://www.devze.com 2023-01-27 20:50 出处:网络
Would there be any copy function available that allows a substring to std::string? Example - const char *c = \"This is a test strin开发者_如何转开发g message\";

Would there be any copy function available that allows a substring to std::string?

Example -

const char *c = "This is a test strin开发者_如何转开发g message";

I want to copy substring "test" to std::string.


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);


Well, you can write one:

#include <assert.h>
#include <string.h>
#include <string>

std::string SubstringOfCString(const char *cstr,
    size_t start, size_t length)
{
    assert(start + length <= strlen(cstr));
    return std::string(cstr + start, length);
}


You can use this std::string's constructor:

string(const string& str, size_t pos, size_t n = npos);

Usage:

std::cout << std::string("012345", 2, 4) << std::endl;

const char* c = "This is a test string message";
std::cout << std::string(c, 10, 4) << std::endl;

Output:

2345
test

(Edit: showcase example)


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;
}


const char *c = "This is a test string message";
std::string str(c);
str.substr(0, 4); 
const char *my_c = str.c_str(); // my_c == "This"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号