Graham
Graham

Reputation: 8181

How to convert part of a char array to a string

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.

Upvotes: 19

Views: 22735

Answers (2)

Habib
Habib

Reputation: 223422

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504122

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

Upvotes: 44

Related Questions