验证字符串格式的函数代码为: Code static void StrWillBeOk(ref String str) { bool toBeContinue = false; string[] strSplit = new string[3]; while (!toBeContinue) { strSplit = str.Split('-'); try { bool strIsOk = true; if (strSplit.Length != 3) strIsOk = false; foreach (string s in strSplit) if (s == "") { strIsOk = false; break; } if (!strIsOk) throw new ArgumentException(); else toBeContinue = true; } catch (ArgumentException e) { Console.WriteLine("格式不正确,请严格按照‘姓名-密码-课程’输入!"); str = Console.ReadLine(); } } } 使用该函数: string TeacherInfo = Console.ReadLine().Trim();StrWillBeOk( ref TeacherInfo); // 验证输入的字符串是否有效 string [] theTeacherInfo = TeacherInfo.Split( ' - ' ); 转载于:https://www.cnblogs.com/zhangzufa/archive/2009/04/21/1440789.html