0

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"
3
  • What's the problem with what you tried? It's something you can find pretty easily, so I assume you have some troubles with the code you wrote. Commented Feb 17, 2014 at 16:49
  • 1
    After understanding that a string is just an array of character, you can get the first character using newarray[1] = array[1][0]; Commented Feb 17, 2014 at 16:54
  • I haven't tried anything, I've asked this because tesseract.getText(); gives me result of a single character(which is the correct one) and puts a "newline" after the character. So instead of array[x] = "A" it turns into array[x] = "A" + newline or nextline Commented Feb 17, 2014 at 16:55

1 Answer 1

3
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)

Sign up to request clarification or add additional context in comments.

4 Comments

My problem is getting the first character of each of the data inside a String array. Not getting the first data inside the string array.
@julianconcepcion, try that code, it would return first character of each data element. It will not return you the first array element
Can I do this array[0][0].toString() ?
@julianconcepcion, yes you can, string itself is treated as array of characters,

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.