简体   繁体   English

在 for 循环中是否可以“继续”foreach 循环?

[英]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.我有一种方法可以检查字符串中的每个字符是否是从 a 到 m 的字母。 I now have to continue a foreach loop, while in a for loop.我现在必须在 for 循环中continue一个 foreach 循环。 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.如果有一个字符不在 a 到 m 的范围内,则错误应该加 1。 In the end, the function should return the number of errors and the number of total characters in the string, fE: "3/17".最后,function 应该返回字符串中的错误数和总字符数,fE: "3/17"。

Edit编辑

What I wanted to achieve is not possible.我想要达到的目标是不可能的。 There are workarounds, demonstrated in BsdDaemon's answer , by using a temporary variable.通过使用临时变量,在BsdDaemon 的回答中展示了一些解决方法。

The other answers fix my issue directly, by simply improving my code.其他答案通过简单地改进我的代码直接解决了我的问题。

i think ('a' == (char)i) should be (c == (char)i) .我认为('a' == (char)i)应该是(c == (char)i)
and why not replace the for with just if((int)c >= 97 && (int)c <= 109) ?为什么不用if((int)c >= 97 && (int)c <= 109)替换for呢? you solution might work but is extremly unperformant您的解决方案可能有效,但性能极差

How about using LINQ:使用 LINQ 怎么样:

int errors = s
    .Count(c => !Enumerable.Range(97, 13).Contains(c));

Then there is no need to break out of the loop.那么就没有必要跳出循环了。

Or to avoid the nested loop altogether, which will improve performance:或者完全避免嵌套循环,这将提高性能:

int errors = s.Count(c => c < 97 || c > 109);

char is implicitly convertible to int so there's no need to cast. char可以隐式转换为int ,因此无需强制转换。

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:在此之后,如果底层逻辑过程的 rest,您可以使用 boolean 继续控制:

    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;
    }

Regular Expressions are perfectly suited to handle this type of "problem" and is considerably more flexible...for one thing you would not be limited to consecutive characters.正则表达式非常适合处理这种类型的“问题”,并且更加灵活……一方面,您不会局限于连续字符。 The following console app demonstrates how to use Regex to extract the desired information from the targeted string.以下控制台应用程序演示了如何使用 Regex 从目标字符串中提取所需信息。

private static string TestSearchTextRegex(string textToSearch)
{
    var pattern = "[^a-m]";
    var ms = Regex.Matches(textToSearch, pattern);

    return $"{ms.Count}/{textToSearch.Length}";
}


NOTE笔记

The pattern "[^am]" basically says: find a match that is NOT (^) in the set of characters.模式“[^am]”基本上是说:在字符集中找到一个不是 (^) 的匹配项。 This pattern could easily be defined as "[^a-mz]" which in addition to characters "am" would also consider "z" to also be a character that would not be counted in the error group.这种模式可以很容易地定义为“[^a-mz]”,除了字符“am”之外,它还认为“z”也是一个不计入错误组的字符。

Another advantage to the Regex solution, you are able to use the actual characters you are looking for as apposed to the number that represents that character. Regex解决方案的另一个优点是,您可以使用您正在寻找的实际字符与代表该字符的数字相对应。

The continue will skip the further lines in that iterations and if you need to break out the loop use break. continue将跳过该迭代中的其他行,如果您需要break循环,请使用 break。

public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if ('a' == (char)i)
            {
                break; // break the whole looping, continue will break only the iteration
            }
        }
        error++;
    }
    string length = Convert.ToString(s.Length);
    return error + "/" + length;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM