拆分字符串中的整数值 [英] Split interger value in the string

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

问题描述

我有一个字符串值,即字符串str =b(2)

我只需要整数值,这意味着我需要一个输出是int value = 2

我该怎么做?

解决方案

使用正则表达式。尝试

 input = Regex.Replace(输入,  [^ 0-9] +  string  .Empty); 


我通常会尝试创建,在这种情况下,目的,可重复使用的小代码工具:

  private   static 正则表达式GetInt = 正则表达式( @  \d +); 

private bool StringToInt32( string str, ref int result)
{
return Int32 .TryParse(GetInt.Match(str).Value, out 结果);
}

// 使用示例:

// int result = 0;
// string aString =b(2);

// if(StringToInt32(aString,ref result))
// {
// int x = 33;
// }


I have a string value, that is string str="b(2)"
I need that integer value only, that mean i need a output is int value = 2
How should i make it?

解决方案

Use regular expressions. Try

input = Regex.Replace(input, "[^0-9]+", string.Empty);


I usually try to create, general-purpose, re-usable, "small" code-tools in situations like this:

private static Regex GetInt = new Regex(@"\d+");

private bool StringToInt32(string str, ref int result)
{       
    return Int32.TryParse(GetInt.Match(str).Value, out result);
} 

// Example of use:

// int result = 0;
// string aString = "b(2)";

// if (StringToInt32(aString, ref result))
// {
//    int x = 33;
// }


这篇关于拆分字符串中的整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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