How can I get a character in a string by index?
Asked Answered
M

2

76

I know that I can return the index of a particular character of a string with the indexof() function, but how can I return the character at a particular index?

Meadowsweet answered 10/3, 2010 at 12:44 Comment(3)
I'm sure I'm missing something, but if you know the character to use when calling indexof() why do you then need to get it from the string? You could just return the character possibly using indexof() to prove it is in the string first.Dree
^ Yes, missing the ability to read. The OP didn't say s/he already has the character, or even anything close to that.Stigmatic
@MikeTwo The OP doesn't know the index of the character.Miracidium
L
104
string s = "hello";
char c = s[1];
// now c == 'e'

See also Substring, to return more than one character.

Lacreshalacrimal answered 10/3, 2010 at 12:46 Comment(0)
L
16

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);
Latham answered 10/3, 2010 at 12:47 Comment(2)
How can I use your second option, (enumerating) but count the chars two at a time? e.g. "4567" will output to "45" first then "67" next. How would I do that? Thanks :)Winther
@Momoro: foreach (string substring in s.Chunk(2)) { ... }. Enumerable.Chunk is built-in in .NET 6+, you can find example implementations for other versions here: https://mcmap.net/q/270201/-how-do-i-chunk-an-enumerable/87698Nonessential

© 2022 - 2024 — McMap. All rights reserved.