141

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#?

1
  • Are you looking for a solution that only works on strings guaranteed not to contain any non-16-bit Unicode characters? Or are you looking for a solution that works on an arbitrary string? Apr 25, 2015 at 1:14

7 Answers 7

243

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];
1
  • 2
    I think it should be pointed out that str.Substring(8,1) works as a solution, but it is much slower. Just found that out the hard way.
    – qzcx
    Feb 28, 2015 at 2:10
23
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#.

0
1

In C#, the string must be static for saying :

str[8];

0

you can use LINQ

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

please try to make it as a character

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

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!

0
-4

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

1
  • Why would you use an IEnumerable extension method, when you can just do what the others mentioned many years ago? (Built-in string indexing). Oct 14, 2017 at 15:49

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.