加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何从C#中的字符串中获取数字?

发布时间:2020-12-16 01:47:54 所属栏目:百科 来源:网络整理
导读:string str="this image has the width of 200px and height of 100px.";int width,height; 我怎样才能获得代码 width= 200;height=100; 如果宽度超过150,我将宽度减小到150,我将计算高度 if(width150){ height=(height*150)/200; width=150;} 结果字符串将
string str="this image has the width of 200px and height of 100px.";
int width,height;

我怎样才能获得代码

width= 200;
height=100;

如果宽度超过150,我将宽度减小到150,我将计算高度

if(width>150)
{
 height=(height*150)/200;
 width=150;
}

结果字符串将是..

str="this image has the width of 150px and height of 75px.";

我知道substring()indexOf()split()

我知道我可以用“宽度”分割字符串,但我不知道如何找到分割字符串的数量.

解决方法

这有几个部分.首先,我建议使用正则表达式来匹配字符串的一部分,并明确地捕获它的数字部分.

例如,可能的正则表达式可能是:

widthsofs(?<width>d+)pxsandsheightsofs(?<height>d+)px

其中“XXXpx的宽度和YYYpx的高度”匹配,其中XXX被捕获为命名组宽度,YYY被捕获为命名组高度.

这是迄今为止的代码:

string str="this image has the width of 200px and height of 100px.";
var regex = new Regex(@"widthsofs(?<width>d+)pxsandsheightsofs(?<height>d+)px");
var match = regex.Match(str);

现在,该匹配有2个组,如前所述,名称为width和height.然后使用可以在捕获组上使用int.Parse来获取值作为数字:

var width = int.Parse(match.Groups["width"].Value);
var height = int.Parse(match.Groups["height"].Value);

最后一部分,改变数字并重新制定你似乎很好掌握的字符串,所以我没有把它包括在内.

以下是演示以上所有内容的实例:http://rextester.com/rundotnet?code=CLPS3633

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读