Reputation: 31
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.
Upvotes: 1
Views: 2567
Reputation: 4883
Yes, you can do that:
string[] s = new string[]{"something", "somethingMore"};
char c = s[0][0];
Upvotes: 1
Reputation: 44
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];
Upvotes: 0
Reputation: 61952
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.
Upvotes: 5