•分别使用goto和不用goto跳出下面的多重循环。使用goto 参考代码:
namespace ConsoleApp1 { internal class Program { static void Main(string[] args) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 6; j++) { Console.WriteLine($"loop-{i}-{j}"); if (i == j + 4) goto M; } } M: Console.WriteLine("finish!"); } } }运行结果:
不使用goto:
namespace ConsoleApp1 { internal class Program { private static int M(int x) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 6; j++) { Console.WriteLine($"loop-{i}-{j}"); if (i == j + 4) return i; } } return -1; } static void Main(string[] args) { int x = 0; Console.WriteLine(M(x)); } } }运行结果:
•使用字典统计下面数据中各个字母出现的次数•【a,b,c,c,c,e,e,e,a,a,c,b,a,r,z,w,t】••如果不使用字典应该怎么实现同样的功能?namespace ConsoleApp3 { internal class Program { static void Main(string[] args) { string str = "a,b,c,c,c,e,e,e,a,a,c,b,a,r,z,w,t"; var dic = new Dictionary<char, int>(); foreach(var item in str) { if (char.IsLetter(item)) { if (!dic.ContainsKey(item)) { dic.Add(item, 1); } else { dic[item]++; } } } foreach(KeyValuePair<Char,int>item in dic) { Console.WriteLine(item.Key + " " + item.Value); } Console.ReadKey(); } } }运行结果:
不使用字典:
using System; using System.Linq; namespace get_first_char_of_string { class Program { static void Main(string[] args) { string source = "a,b,c,c,c,e,e,e,a,a,c,b,a,r,z,w,t"; int count = source.Split('o').Length - 1; Console.WriteLine(count); } } }•这段代码的作用是?•必须逆序吗?为什么?看到这里的你,是不是要想想我是谁呢?
C#分别使用goto和不用goto跳出多重循环
于 2023-03-20 23:22:09 首次发布
文章对比了在C#中使用goto语句和不使用goto语句跳出多重循环的方法,并提供了两种实现方式的代码示例。此外,还展示了如何使用字典统计字符串中各字母出现的次数,以及如果不使用字典,如何通过其他方法(如LINQ)实现相同功能。





433

被折叠的 条评论
为什么被折叠?



