Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 847
user963241 Avatar asked Nov 28 '10 16:11

user963241


People also ask

How do I copy a substring to another 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.

How do I copy a character from a string in C++?

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

How do I get const char from STD string?

You can use the c_str() method of the string class to get a const char* with the string contents.


2 Answers

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);
like image 193
Dmitry Avatar answered Oct 07 '22 16:10

Dmitry


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;
}
like image 32
Toby Speight Avatar answered Oct 07 '22 18:10

Toby Speight