julianconcepcion
julianconcepcion

Reputation: 187

How to get the first string of each of the data inside a String array?

If I have a string array String[] array = new String[3]; , how do I get the first characters of each of the data inside that array and store in a new string array String[] newarray = new String[3];

For example:

array[0] = AB;
array[1] = AB;
array[2] = AB;
array[3] = AB;

I must get all 4 letter "A" because it is the first character in each of the data inside my String[].

So it must be like this:

newarray[0] = first character of array[0] //which is "A"
newarray[1] = first character of array[1] //which is "A"
newarray[2] = first character of array[2] //which is "A"
newarray[3] = first character of array[3] //which is "A"

Upvotes: 0

Views: 110

Answers (1)

Habib
Habib

Reputation: 223257

var newArray = array.Select(r=> r[0].ToString()).ToArray();

This assuming that you don't have null or empty string "" in any of your array element. If there are null or empty strings in your array element and you want to ignore those in the final result you can do:

var newArray = array
            .Where(r=> !string.IsNullOrEmpty(r))
            .Select(r => r[0].ToString())
            .ToArray();

if you want to consider any white space as empty string then you can replace string.IsNullOrEmpty with string.IsNullOrWhiteSpace (supported with .Net framework 4.0 or higher)

Upvotes: 3

Related Questions