好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#利用正则判断输入是否为纯数字、容器类

容器类、正则表达式在几乎所有编程语言都存在的东西。很常用也很使用。下面用如下的一个控制台小程序说明C#的正则表达式与容器类的应用。

开始直接输出在C#定义好的数据字典Dictionary,这就是Java与Python的HashMap,之后定义一个存int的List,让用户无限输入这个List的元素,输入到#则停止输入,在输入的过程中遇到不是纯输入,则拒绝这个输入。
 遍历这个List输出,之后利用C#的另一个容器HashSet为这个List去重。 

这个程序的代码如下,其实以上所有的东西都在以前的文章说过。这主要是将这种思想写成C#语言而已。 
关于 正则表达式 可以参考:《 js利用正则表达式检验输入内容是否为网址 》
关于 利用HashSet为List去重 :《 Java中ArrayList的使用方法简单介绍 》

?

using System;

using System.Collections.Generic; //用到了容器类

using System.Text.RegularExpressions; //用到了正则表达式

 

class Collections

{

  //C#容器Dictionary的基本使用

  public static void dictionaryTest() {

  Dictionary< string , int > dict = new Dictionary< string , int >();

  dict.Add( "K1" , 123);

  dict[ "K2" ] = 456;

  dict.Add( "K3" , 789);

  Console.WriteLine( "数据字典dict中的Key-value对为:" );

  foreach (KeyValuePair< string , int > k in dict)

  {

   Console.WriteLine( "{0}-{1}; " , k.Key, k.Value); //K1-123; K2-456; K3-789;

  }

  }

 

  //C#容器List与HashSet的基本使用

  public static void listTest() {

 

  List< int > list = new List< int >();

 

  Console.WriteLine( "输入#,结束输入!" );

  Regex regex = new Regex( "^[0-9]*$" );

  String input_string = "" ;

  while ( true )

  {

   Console.Write( "请输入数组的数字:" );

   input_string = Console.ReadLine();

   if (input_string.Trim().CompareTo( "#" ) == 0)

   {

   break ;

   }

   else

   {

   if (regex.IsMatch(input_string)) //利用正则表达式判断是否输入的是数字

   {

    list.Add( int .Parse(input_string));

   }

   else

   {

    Console.WriteLine( "输入的不是数字!请重新输入!" );

   }

   }

  }

  Console.WriteLine( "输入的List为:" );

  for ( int i = 0; i < list.Count; i++)

  {

   Console.Write(list[i] + " " );

  }

  Console.WriteLine();

 

  list = new List< int >( new HashSet< int >(list)); //利用集合为list去重

 

  Console.WriteLine( "List利用Set去重后为:" );

  for ( int i = 0; i < list.Count; i++)

  {

   Console.Write(list[i] + " " );

  }

  Console.WriteLine(); ;

 

  }

 

  public static void Main(String[] args)

  {

  dictionaryTest();

  listTest();

  Console.ReadKey(); //等待用户按回车才结束程序

  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

dy("nrwz");

查看更多关于C#利用正则判断输入是否为纯数字、容器类的详细内容...

  阅读:44次