19

I want to convert part of a char array to a string. What is the best way to do that.

I know I can do the following for the whole array

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);

but what about just elements 2 to 4 for example?

I also know I can loop through the array and extract them, but I wondered if there was a more succinct way of doing it.

2 Answers 2

44

Use the String constructor overload which takes a char array, an index and a length:

String text = new String(chars, 2, 3); // Index 2-4 inclusive
Sign up to request clarification or add additional context in comments.

Comments

1

You may use LINQ

char[] chars = { 'a', ' ', 's', 't', 'r', 'i', 'n', 'g' };
string str = new string(chars.Skip(2).Take(2).ToArray());

But off course string overloaded constructor is the way to go

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.