decrement a foreach

  • Thread starter Thread starter Elementary Penguin
  • Start date Start date
E

Elementary Penguin

is there a way to decrement a foreach loop?

for example

string s = "cat";

foreach(char c in s)
//some how it goes backward here
Console.WriteLine(c);

and so the result would be

t
a
c
 
Hi,

Why you think you go forwards?

You are sure you go forwards with
for i as integer = 0 to Cat.length-1
Cat(i)
next

Cor
 
Why not use a for loop?

string s = "cat";

for (int i = s.Length-1; i >= 0; i--)
Console.WriteLine(s.Substring(i,1));
 
Sorry,

I thought I was answering from the general newsgroup otherwise I would have
done it in C#, however Mick did that already

Cor
 
You could optionally resort the string in the reverse order and then run your
foreach loop as usual. eg.

class ReversedComparer:IComparer
{
public int Compare(object x,object y)
{
if((char)x < (char)y)
return 1;
else if((char)x > (char)y)
return -1;
else
return 0;
}
}


Array array = s.ToCharArray();
Array.Sort(array,new ReversedComparer());
//s = new String((char[])array);

foreach(char c in array)
{
Console.WriteLine(c);
}
 
Mick said:
Why not use a for loop?

I like having access to the iterator in the body of the for code.

So, being able to use char r, and having it be indexxed, is a real benefit.

I guess the solution is to pass in a reversed string, but that seems really
inefficient.

I guess this is why the c people invented pointers...
 
couple of options:

1~ go backward:
for(int i=s.Length-1; i>=0; i--)
Console.WriteLine(s);

2~ use a Stack:
Stack stack = new Stack();
foreach(char c in s)
stack.Push(c);
while(stack.Count>0)
Console.WriteLine((char)stack.Pop());

F.O.R.
 
Elementary Penguin said:
I like having access to the iterator in the body of the for code.

So, being able to use char r, and having it be indexxed, is a real benefit.

Just use the indexer of the string:

for (int i=s.Length-1; i >= 0; i--)
{
char r = s;
// ...
}

At that point you can do everything you could with a foreach, and more,
as you know the index (which you don't with foreach).
I guess the solution is to pass in a reversed string, but that seems really
inefficient.

If you really wanted to use foreach and you're only interested in
strings, you could always your own enumerator which iterates through a
string's characters backwards.
 
Olorin,
2~ use a Stack:
Stack stack = new Stack();
foreach(char c in s)
stack.Push(c);
while(stack.Count>0)
Console.WriteLine((char)stack.Pop());
Little bit crazy to use, however nice as sample.

:-)

Cor
 
Back
Top