如何在C#中的字符串获得数 [英] How to get number from string in C#

查看:121
本文介绍了如何在C#中的字符串获得数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML(3跳闸1-3)的字符串我如何得到3号(前行),并将其转换为int.I想用它作为一个计数



找到这段代码

 公共静态字符串GetNumberFromStr(字符串str)
{
海峡= str.Trim();
匹配M = Regex.Match(STR,@^ [\ \ + - ] * \d \的[EE] [\ \ + - ]????\d * $);
回报(m.Value);
}



但它只能得到1号


< DIV CLASS =h2_lin>解决方案

正则表达式是在您的案件不必要的开销。试试这个:

  INT ExtractNumber(字符串输入)
{
INT数= Convert.ToInt32(输入.Split('')[2]);
返回数;
}



其它有用的Google的方法:

 如果失败
INT I = int.Parse(someString)//抛出异常;

如果失败//返回false,返回true,改变`i`如果成功
布尔B = int.TryParse(someString,出一);

//这个人是能够任意数值Unicode字符转换为双。返回-1如果失败
双倍二级= char.GetNumericValue('2')


i have a String in HTML (1-3 of 3 Trip) how do i get the number 3(before trip) and convert it to int.I want to use it as a count

Found this code

public static string GetNumberFromStr(string str)
{
  str = str.Trim();
  Match m = Regex.Match(str, @"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$");
  return (m.Value);
}

But it can only get 1 number

解决方案

Regex is unnecessary overhead in your case. try this:

int ExtractNumber(string input)
{
    int number = Convert.ToInt32(input.Split(' ')[2]);
    return number;
}

Other useful methods for Googlers:

// throws exception if it fails
int i = int.Parse(someString);

// returns false if it fails, returns true and changes `i` if it succeeds
bool b = int.TryParse(someString, out i);

// this one is able to convert any numeric Unicode character to a double. Returns -1 if it fails
double two = char.GetNumericValue('٢')

这篇关于如何在C#中的字符串获得数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆