如何从C#中的字符串中获取数字?
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()
我知道我可以用“宽度”分割字符串,但我不知道如何找到分割字符串的数量。
这有几个部分。 首先,我建议使用正则表达式来匹配字符串的一部分,并明确地捕获它的数字部分。
例如,可能的正则表达式可能是:
width\sof\s(?\d+)px\sand\sheight\sof\s(?\d+)px
其中“XXXpx的宽度和YYYpx的高度”匹配,其中XXX被捕获为命名组width
,YYY被捕获为命名组height
。
这是迄今为止的代码:
string str="this image has the width of 200px and height of 100px."; var regex = new Regex(@"width\sof\s(?\d+)px\sand\sheight\sof\s(?\d+)px"); var match = regex.Match(str);
现在,该match
有两组名为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
你可以这样做:
string str = "this image has the width of 200px and height of 100px."; string[] numbers = Regex.Split(str, @"\D+"); // let's say 100x100 is default, so if TryParse fails you get 100x100 int width = 100; int height = 100; if (numbers.Length > 1) { Int32.TryParse(numbers[0], out width); Int32.TryParse(numbers[1], out height); }
您可以进行正则表达式匹配并保存200 + 100。
Dim match As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(str, "this image has the width of (\d+)px and height of (\d+)px.")
然后,查看以下值:
match.Groups(0).Value match.Groups(1).Value
对于C#来说
match.Groups[0].Value; match.Groups[1].Value;
如果字符串的格式总是那样,那么它就变成了一个相当简单的任务。 你基本上只需要用“”分隔字符串作为分隔符,并从位置6和10的结果数组中获取字符串。然后只需将最后2个字符“px”和TryParse减去int。 你拥有了它。 或者只是使用一些花哨的正则表达式,就像其他人肯定会建议的那样。
int.Parse(string)或int.TryParse(string,out int)可能是您要用于将字符串转换为int的方法。
例如:
int width; if (int.TryParse (widthString, out width) == true) { Console.WriteLine ("The width is {0}", width); } else { Console.WriteLine ("{0} could not be converted to an int.", widthString); }
使用正则表达式,匹配方法
string str = "this image has the width of 200px and height of 100px."; var numbers = Regex.Matches(str,@"\d+"); int no1, no2; if (numbers.Count == 2) { int.TryParse(numbers[0].Value, out no1); int.TryParse(numbers[1].Value, out no2); }