3

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'

4 Answers4

6

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);
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

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'
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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

 std::string str(ch, ch + 5);
Gábor Buella
  • 1,840
  • 14
  • 22
0

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;
}
dspfnder
  • 1,135
  • 1
  • 8
  • 13