Search code examples
c#for-loopforeachnested-loopscontinue

Is it possible to `continue` a foreach loop while in a for loop?


Okay, so what I want to do should sound pretty simple. I have a method that checks every character in a string if it's a letter from a to m. I now have to continue a foreach loop, while in a for loop. Is there a possible way to do what I want to do?

public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if (c == (char)i)
            {
                // Here immediately continue the upper foreach loop, not the for loop
                continue;
            }
        }
        error++;
    }

    int length = s.Length;
    return error + "/" + length;
}

If there's a character that's not in the range of a to m, there should be 1 added to error. In the end, the function should return the number of errors and the number of total characters in the string, f.E: "3/17".

Edit

What I wanted to achieve is not possible. There are workarounds, demonstrated in BsdDaemon's answer, by using a temporary variable.

The other answers fix my issue directly, by simply improving my code.


Solution

  • You can do this by breaking the internal loop, this means the internal loop will be escaped as if the iterations ended. After this, you can use a boolean to control with continue if the rest of the underlying logic processes:

        public static string Function(String s)
        {
            int error = 0;
            foreach (char c in s)
            {
                bool skip = false; 
    
                for (int i = 97; i <= 109; i++)
                {
                    if ('a' == (char)i)
                    {
                        skip = true;
                        break;
                    }
                }
    
                if (skip) continue;
                error++;
            }
            string length = Convert.ToString(s.Length);
            return error + "/" + length;
        }