c#删除空白和连字符

本文关键字:连字符 空白 删除 | 更新日期: 2023-09-27 17:53:32

嗨,我是一个c#初学者。

需要帮助在编写小代码程序控制台邀请用户输入他们的电话号码没有空格和连字符(-)做验证,如果用户没有遵守这些条件,显示一个错误消息。并创建一个循环,将重新要求用户输入相同的信息再试一次。

Console.WriteLine("Please enter your phone no.: 't");
            string n = Console.ReadLine();
            char[] delimiters = new char[] { ' ', '-' };
            string textBox = Convert.ToString(n);
            string[] numtel = textBox.Split(delimiters);
            bool test = false;

c#删除空白和连字符

这是您的任务的简单解决方案:

bool isValid = false;
while(!isValid){
  Console.WriteLine("Please enter your phone no.: 't");
  string phone = Console.ReadLine();  
  isValid = !string.isNullOrWhiteSpace(phone) 
            && phone.s.IndexOfAny(new[] { '-', ' ' }) < 0;
  if (!isValid)
     Console.WriteLine("No spaces or '-' allowed");
}

然而,这是一种验证电话号码的糟糕方式。人们使用'(','。'和其他字符。

另一种方法是使用正则表达式,例如:
  isValid = !string.isNullOrWhiteSpace(phone)
             && Regex.IsMatch(phone, @"'(?'d{3}')?-? *'d{3}-? *-?'d{4}");

需要一个while循环:

char[] delimiters = new char[] { ' ', '-' };
string n;
while(true)
{
    Console.WriteLine("Please enter your phone no.: 't");
    n = Console.ReadLine();
    if(n.Length > 0 && !n.Any(delimiters.Contains)) break;
    else Console.WriteLine("Invalid value, try again.");
}

Try This:

var compareStrings = new [] { "-", " " };
string phoneNo=string.Empty;
do
{
    Console.WriteLine("enter phone number without spaces and hyphens ");
    phoneNo = Console.ReadLine();
}while(!(compareStrings.Any((c=>phoneNo.Contains(c)))));