C# equivalent to Java's charAt()?

C#JavaString

C# Problem Overview


I know we can use the charAt() method in Java get an individual character in a string by specifying its position. Is there an equivalent method in C#?

C# Solutions


Solution 1 - C#

You can index into a string in C# like an array, and you get the character at that index.

Example:

In Java, you would say

str.charAt(8);

In C#, you would say

str[8];

Solution 2 - C#

string sample = "ratty";
Console.WriteLine(sample[0]);

And

Console.WriteLine(sample.Chars(0));
Reference: http://msdn.microsoft.com/en-us/library/system.string.chars%28v=VS.71%29.aspx

The above is same as using indexers in c#.

Solution 3 - C#

you can use LINQ

string abc = "abc";
char getresult = abc.Where((item, index) => index == 2).Single();

Solution 4 - C#

please try to make it as a character

string str = "Tigger";
//then str[0] will return 'T' not "T"

Solution 5 - C#

Console.WriteLine allows the user to specify a position in a string.

See below sample code:

string str = "Tigger";
Console.WriteLine( str[0] ); //returns "T";
Console.WriteLine( str[2] ); //returns "g";

There you go!

Solution 6 - C#

Simply use String.ElementAt(). It's quite similar to java's String.charAt(). Have fun coding!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrattyView Question on Stackoverflow
Solution 1 - C#ZachView Answer on Stackoverflow
Solution 2 - C#shahkalpeshView Answer on Stackoverflow
Solution 3 - C#Harshad KaremoreView Answer on Stackoverflow
Solution 4 - C#swapnil rawatView Answer on Stackoverflow
Solution 5 - C#AndrewJames57View Answer on Stackoverflow
Solution 6 - C#Nguyễn Trần HiểnView Answer on Stackoverflow