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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Advaitha
  • 31
  • 9

3 Answers3

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.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
1

Yes, you can do that:

string[] s = new string[]{"something", "somethingMore"};
char c = s[0][0];
NicoRiff
  • 4,803
  • 3
  • 25
  • 54
  • 2
    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. – O. R. Mapper Feb 01 '17 at 20:41
  • This satisfies the question. Not sure why it is down voted. – Rinktacular Feb 01 '17 at 20:43
  • 1
    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. – Kenneth K. Feb 01 '17 at 20:46
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];