首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

字符串相加解决办法

2012-08-21 
字符串相加有如下字符串可能值为510ml20ML120ml*4360+120ML360+100ml500ML+300ML如何转换对应为5102012048

字符串相加
有如下字符串可能值为
5
10ml
20ML
120ml*4
360+120ML
360+100ml
500ML+300ML
如何转换对应为
5
10
20
120
480
460
800


[解决办法]
下面可以将每行的数组提取出来,不过你要处理一下运算符号,乘除加减,或者你改用其他方法

C# code
            StreamReader reader = new StreamReader("c:\\1.txt",Encoding.Default);            while (!reader.EndOfStream)            {                int num = 0;                string str = reader.ReadLine();                Regex reg = new Regex(@"(?is)\d+");                MatchCollection mc = reg.Matches(str);                foreach (Match m in mc)                {                    num += Convert.ToInt32(m.Value);                }                MessageBox.Show(num.ToString());            }
[解决办法]
^\d+就可以了。
[解决办法]
应该没什么简单的办法吧

C# code
string text = @"5                            10ml                            20ML                            120ml*4                            360+120ML                            360+100ml                            500ML+300ML";            text = Regex.Replace(text, "[a-zA-Z]", "");            text = Regex.Replace(text, @"(?!\d+)(\*.*)", "");            var matches = Regex.Matches(text, @"(\d+)(\+(\d+))*");            foreach (Match match in matches)            {                if (match.Groups[2].Success)                    Console.WriteLine(Convert.ToInt32(match.Groups[1].Value)                    +                     Convert.ToInt32(match.Groups[3].Value));                else                    Console.WriteLine(Convert.ToInt32(match.Groups[1].Value));            }
[解决办法]
C# code
string[] source = {    "5",    "10ml",    "20ML",    "120ml*4",    "360+120ML",    "360+100ml",    "500ML+300ML",};System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"([^\d\+\*])|(\*\d+)");System.Data.DataTable dt = new System.Data.DataTable();foreach (string s in source){    string result = dt.Compute(reg.Replace(s, string.Empty), null).ToString();}
[解决办法]
C# code
string[] strs ={ "5",                                "10ml",                                "20ML",                                "120ml*4",                                "360+120ML",                                "360+100ml",                                "500ML+300ML"};                foreach (string str in strs)                {                                       var filteredStr=Regex.Replace(str,@"[^\d+*?\d+]", "");                    MatchCollection ms = new Regex(@"(?<!.+)\d+|(?<=\+)\d+").Matches(filteredStr);                    int num = 0;                    foreach (Match r in ms) { num += int.Parse(r.Value); };                    Response.Write(num+"<br/>"); 

热点排行