user1018517
user1018517

Reputation:

C++ Best way to create a new string from index of char array?

I got a chars array like

char ch[] = "This is a char array";

and I want to make a new string from index n to index j, for i.e.

string str = stringFromChar(ch, 0, 5); //str = 'This'

Upvotes: 3

Views: 4656

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

You can just write

string str(ch, ch + 5); //str = 'This'

That is the general form will look like

string str(ch + i, ch + j); //str = 'This'

where i < j

If the first index is equal to 0 then you can also write

string str(ch, n );

where n is the number of characters that you are going t0 place in the created object. For example

string str( ch, 4 ); //str = 'This'

Or if the first index is not equal to 0 then you can also write

string str( ch + i, j - i ); //str = 'This'

Upvotes: 2

dspfnder
dspfnder

Reputation: 1123

You can just use the begin and end functions...

#include<iostream>
#include<string>

int main() {

    char ch[] = "This is a char array";
    std::string str(std::begin(ch), std::end(ch));
    std::cout << str << std::endl;

    // system("pause");
    return 0;
}

Upvotes: 0

G&#225;bor Buella
G&#225;bor Buella

Reputation: 1920

Just use the constructor with iterators ( also, char* is a valid input iterator )

 std::string str(ch, ch + 5);

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117866

You could use the constructor for std::string that takes two iterators.

std::string str(std::begin(ch), std::next(std::begin(ch), 5));

Working demo

In the more general case, you could use std::next for both the start and end iterator to make a string from an arbitrary slice of the array.

I prefer to use the C++ Standard Library when applicable, but know that you could do the same thing with pointer arithmetic.

std::string str(ch, ch+5);

Upvotes: 6

Related Questions