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?
How can I get a character in a string by index?
string s = "hello";
char c = s[1];
// now c == 'e'
See also Substring
, to return more than one character.
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);
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/87698 –
Nonessential © 2022 - 2024 — McMap. All rights reserved.
indexof()
why do you then need to get it from the string? You could just return the character possibly usingindexof()
to prove it is in the string first. – Dree