1

I have a string array, I want to access the characters of the first element in that array:

string[] str= new string[num];

for(int i = 0; i < num; i++)
{
    str[i] = Console.ReadLine();
}

To access the characters of the first element in the string array, in Java

str[0].CharAt[0] // 1st character

Is there a way in C# for this? The only function I could see was use of substring. It will incur more overhead in such case.

4
  • 2
    Possible duplicate of how to return the character which is at the index? Commented Feb 1, 2017 at 20:36
  • 1
    @Rinktacular: "which will print out one character at a time" - nope, because str is an array of strings, not a single string. Commented Feb 1, 2017 at 20:40
  • Oops.. good catch. Misread the Declaration. :) Commented Feb 1, 2017 at 20:42
  • @Rintacular this doesn't solve, I want to access character of a string in the array Commented Feb 1, 2017 at 20:42

3 Answers 3

5

You would use:

str[0][0]

where the first [0] is accessing the 0th array member, while the next [0] is the indexer defined by System.String which gives the 0th char value (UTF-16 code unit) of the string.

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

Comments

1

Yes, you can do that:

string[] s = new string[]{"something", "somethingMore"};
char c = s[0][0];

3 Comments

What's the downvote on this answer for? It surely answers the question, even if the example is not directly copy-and-pasteable into the OP's code.
This satisfies the question. Not sure why it is down voted.
Didn't downvote, but it doesn't answer the question. The question is about the characters inside a string inside an array. Your answer is just the characters inside the string. You're missing the array part.
0

You could convert the first string of the string array to a character array and simply get the first value of the character array.

string[] stringArray = {"abc"};
char[] charArray = stringArray[0].ToCharArray();
char first = charArray[0];

3 Comments

There is no need to copy the entire string contents over into a new array if you just want the first char.
Why make this into a char array?
I didn't know you could index on a string like the other answers show. Thanks!

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.