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.
We can convert char to String in java using String. valueOf(char) method of String class and Character. toString(char) method of Character class.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With