Ryan Evans
Ryan Evans

Reputation: 19

C# Finding the index of a specific iteration of a char

I'm trying to create a program that will loop through every character in a string and state that characters specific index

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("enter");
            string expression = Console.ReadLine();

            foreach(char c in expression)
            {
                if (c == '+')
                {
                    Console.WriteLine("plus detected! :{0}",expression.IndexOf(c));
                }
            }

            Console.ReadLine();
        }
    }
}

The problem with my code is that it doesn't say the index of the specific '+' it's up to in the loop, but instead states the first instance of the '+'

How can this be fixed to instead say the specific index

(eg. 1+2+3+4+5 should yield "1,3,5,7", the indexes(?) of each '+')

Upvotes: 0

Views: 105

Answers (4)

Michał Turczyn
Michał Turczyn

Reputation: 37367

This slight modification will solve your problem, whlie preserving your original code:

//you could even use byte for this to save memory :)
int index = -1;
Console.WriteLine("enter");
string expression = Console.ReadLine();

foreach (char c in expression)
    if (c == '+')
        Console.WriteLine("plus detected! :{0}", (index = expression.IndexOf(c,index + 1)));

Console.ReadLine();

Upvotes: 0

Christian Huber
Christian Huber

Reputation: 818

You could use a for loop to iterate the expression:

for(int i = 0; i < expression.length; i++) 
{
    if (expression[i] == '+')
    {
        Console.WriteLine("plus detected! :{0}", i);
    }
}

Or you introduce a custom counter

int i = 0;

foreach(char c in expression)
{
    if (c == '+')
    {
         Console.WriteLine("plus detected! :{0}", i);
    }
    i++;
}

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56423

The simplest solution would be to use a for loop as suggested by @Ali Ezzat Odeh. Another solution would be using Enumerable.Range:

var indices = Enumerable.Range(0, expression.Length)
                        .Where(index => expression[index] == '+');

foreach(var index in indices)
     Console.WriteLine(index);

Upvotes: 4

Ali Ezzat Odeh
Ali Ezzat Odeh

Reputation: 2163

I suggest using for loop:

for(int i = 0; i < expression.Length; i++){
  if(expression[i]== '+'){
     Console.WriteLine("plus detected! :{0}",i);
  }
}

Upvotes: 4

Related Questions