C# 在字符串中提取数字

来源:互联网 发布:良心社交网游知乎 编辑:程序博客网 时间:2024/05/21 06:14

C# 在字符串中提取数字

c# 获取字符串中的数字
///
/// 获取字符串中的数字
///
/// 字符串
/// 数字
例子1:

public static decimal GetNumber(string str)
{
    decimal result = 0;
    if (str != null && str != string.Empty)

   {

// 正则表达式剔除非数字字符(不包含小数点.)
    str = Regex.Replace(str, @"[^\d.\d]", "");
// 如果是数字,则转换为decimal类型
    if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$"))
    {
    result = decimal.Parse(str);
    }
 }
   return result;
}
例子2:
///
/// 获取字符串中的数字
///
/// 字符串
/// 数字
public static int GetNumberInt(string str)
{
int result = 0;
if (str != null && str != string.Empty)
{
// 正则表达式剔除非数字字符(不包含小数点.)

str = Regex.Replace(str, @"[^\d.\d]", "");

// 如果是数字,则转换为decimal类型

if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$"))

{

result = int.Parse(str);

}

}

return result;

}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jiaao/archive/2008/07/09/2628982.aspx
 离子3:
 public string IsNum(String str)

    {

        string ss="";

        for (int i = 0; i < str.Length; i++)

        {
            if (Char.IsNumber(str, i) == true)
            {
                ss += str.Substring(i, 1);
            }
            else
            {
                if (str.Substring(i, 1) == ",")
                {
                    ss += str.Substring(i, 1);
                }
            }
        }
        return ss;
    }

 Console.Write(IsNum("aaa139504928bbb11ccc,888"));//你们看下效果就知道了.

说明:

使用正则表达式的效果:

            string str1 = "Cycle Layer: 0";

            string str11 = "Cycle Nr.: 0";

            string str2 = Regex.Replace(str1, @"[^\d.\d]", "");//包括小数点

            string str22 = Regex.Replace(str11, @"[^\d\d]", "");//不包括小数点

DateTime.Now.ToLongDateString()   //日期  

DateTime.Now.ToLongTimeString()     //时间

   DateTime datetime = DateTime.Now.ToLocalTime();    //{2010-1-22 18:36:35}

            string str0 = datetime.Date.ToString();//"2010-1-22 0:00:00"

            string strf1 = DateTime.Now.ToLongDateString();  //   "2010年1月22日"

            string strf2 = DateTime.Now.ToLongTimeString();   //"18:38:32"

            DateTime str3 = datetime.Date;   //{2010-1-22 0:00:00}

            string str4 = DateTime.Now.ToShortDateString();   //"2010-1-22"

使用Linq来提取也非常方便。
public static void GetDigitFromString()
{
     //字符串数据源

     string str ="abc.htm?id=16034$a=343";

     //查询字符串中是数字的查询语句

     var query = from ch in strr
                 where Char.IsDigit(ch)
                 select ch;
 
     //执行查询并输出结果

     foreach (var ch in query)
     {
         Console.WriteLine(ch+",");
     }
     Console.Read();
}
0 0
原创粉丝点击