Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert part of a char array to a string

Tags:

c#

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.

like image 399
Graham Avatar asked Nov 02 '12 07:11

Graham


People also ask

How do you parse a char to a string?

We can convert char to String in java using String. valueOf(char) method of String class and Character. toString(char) method of Character class.

Can we convert array to string?

Convert Array to String. Sometimes we need to convert an array of strings or integers into a string, but unfortunately, there is no direct method to perform this conversion. The default implementation of the toString() method on an array returns something like Ljava. lang.


2 Answers

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
like image 185
Jon Skeet Avatar answered Oct 09 '22 18:10

Jon Skeet


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

like image 20
Habib Avatar answered Oct 09 '22 19:10

Habib