简体   繁体   中英

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

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.

You can use a std::string iterator constructor to initialize it with a substring of a C string eg:

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"

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