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?
            Asked
            
        
        
            Active
            
        
            Viewed 2e+01k times
        
    69
            
            
         
    
    
        Ivar
        
- 6,138
- 12
- 49
- 61
 
    
    
        SmartestVEGA
        
- 8,415
- 26
- 86
- 139
- 
                    1I'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. – Mike Two Mar 10 '10 at 12:49
- 
                    3^ Yes, missing the ability to read. The OP didn't say s/he already has the character, or even anything close to that. – Jim Balter Mar 15 '17 at 06:01
- 
                    @MikeTwo The OP **doesn't** know the index of the character. – Ctrl S Mar 04 '19 at 15:18
2 Answers
97
            string s = "hello";
char c = s[1];
// now c == 'e'
See also Substring, to return more than one character.
 
    
    
        Tim Robinson
        
- 53,480
- 10
- 121
- 138
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);
 
    
    
        Brian Rasmussen
        
- 114,645
- 34
- 221
- 317
- 
                    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 :) – Momoro Apr 21 '21 at 00:22
- 
                    @Momoro: `foreach (string substring in s.Chunk(2)) { ... }`. [Enumerable.Chunk](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.chunk?view=net-6.0) is built-in in .NET 6+, you can find example implementations for other versions here: https://stackoverflow.com/q/12389203/87698 – Heinzi Feb 01 '22 at 08:54