从字符串中提取数值 [英] extracting numeric values from a string

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

问题描述

你好,

请问我如何从一个字符串中提取所有数字值并将所有提取的值相加.例如

字符串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

推荐答案

非常好又容易此处为逻辑 [ ^ ]即可从内部获取所有数字一个字符串.
将所有数字放入数组或集合中后,只需将它们加在一起即可.
Very nice and easy logic here[^] to get all numbers from within a string.
Once you have all the numbers in an array or collection, just add them together.


示例:

example:

<code>
<pre lang="cs">
const string myInteger = "[0-9]&quot;;


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;


希望它有助于解决您的问题,
Hope it helps to solve your problem,
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);
    }
}


:)


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

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