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'
1
  • 1
    char[] ch this is not a valid syntax. maybe in C#, but not in C++ Commented Oct 25, 2015 at 15:37

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

BTW, what is diffrent between std::next(std::begin(ch), 5) and std::begin(ch)+ 5 ?
@HumamHelfawi std::next and std::advance handle advancing through a container that may or may not use contiguous memory (i.e. a std::list, etc).
Oh my god I was always using the + way and I thought that my code run for any container.. Foolish me! Thanks!
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'

Comments

0

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.