本文介绍了从字符串中提取数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
请问我如何从一个字符串中提取所有数字值并将所有提取的值相加.例如
字符串myWord ="This一个示例文本4,其中包含9个单词";
我要如何得出4和9,然后将它们加起来总计为13
在此先感谢
您忠实的
Martin
Hi there,
Please how can i extract all numeric values from a string and add up all the extracted values. E.g
string myWord="This a sample text 4 that contains 9 words ";
How do i get out 4 and 9, and then add them up to get 13 as total
Thanks in advance
Yours faithfully
Martin
推荐答案
<code>
<pre lang="cs">
const string myInteger = "[0-9]";
private void button1_Click(object sender, EventArgs e)
{
String myString = textBox1.Text;
String somInteger = string.Empty;
string tmpString = string.Empty;
Int32 summedValue = 0;
foreach (char value in textBox1.Text)
{
if (value.ToString().Trim().Equals(string.Empty) && !tmpString.Equals(string.Empty))
{
summedValue += Convert.ToInt32(tmpString);
tmpString = string.Empty;
}
if (IsInteger(value))
tmpString += value.ToString();
}
if (!tmpString.Equals(string.Empty))
summedValue += Convert.ToInt32(tmpString);
MessageBox.Show(summedValue.ToString());
}
private bool IsInteger(char value)
{
return Regex.IsMatch(value.ToString(), myInteger);
}
不要忘记:
don''t forget the:
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string myWord = "This a sample text 4 that contains 9 words ";
string[] numbers = Regex.Split(myWord, @"\D+");
int parsedValue = 0;
int result = numbers.SkipWhile(item => string.IsNullOrEmpty(item)).Sum(item => Int32.TryParse(item, out parsedValue) ? parsedValue : parsedValue);
}
}
:)
这篇关于从字符串中提取数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!