如何循环字符串并转换其中的数字。 [英] How do I loop through a string and convert figures in it.

查看:118
本文介绍了如何循环字符串并转换其中的数字。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好



我想将带有'结尾的数字换成字符串中的米。



例如我有



核心从239'-242'突破:23'-28',核心回收率为25%。



我想要这个



核心从72.85-73.76:7.01-8.53大幅突破,核心回收率为25 %。



我需要帮助。

解决方案

我的头顶:



 使用 System.Text.RegularExpressions; 

静态 字符串转换( string value
{
return Regex.Replace(< span class =code-sdkkeyword> value , @ ([\d。] +) ',m = >
float .Parse(m。组[ 1 ]。值)* 0 3048 + // 将英尺转换为米
m.Groups [ 2 ]。成功? float .Parse(m.Groups [ 1 ]。值)* 0 0254 0 // 将英寸转换为米。
).ToString());
}





说的是:



  • 查找所有事件
  • 将数值转换为米。
  • 替换所有出现次数。


< blockquote>首先,用正则表达式提取你的数字结尾 -

然后你可以使用Regex.Match重载,它将MatchEvaluator作为第二个参数,将每个匹配单独地提供给一个函数,返回新字符串。

正则表达式正则表达式= 正则表达式( @  \d +(?=')); 
string replacement = regex.Replace(inputString, new MatchEvaluator(ReplaceMatch));

ReplaceMatch方法将遵循:

  private   string  ReplaceMatch(匹配m)
{
double feet = .Parse(m.Value);
return string .Format( {0:N2},feet * 0 3048 );
}


您可以使用字符串上的Split()方法拆分它们。拆分'然后循环结果。



类似于:



  foreach 字符串 str  in  stringVar.Split( '))
{
// 做你的事
}


Hi All

I want to convert figures with ending with "'" to meters in a string.

e.g I have

The core heavily broken from 239'-242': 23'-28' with a core recovery of 25%.

I want this

The core heavily broken from 72.85-73.76: 7.01-8.53 with a core recovery of 25%.

Please I need help.

解决方案

Off the top of my head:

using System.Text.RegularExpressions;

static string Convert(string value)
{
    return Regex.Replace(value, @"([\d.]+)'", m => (
        float.Parse(m.Groups[1].Value) * 0.3048 +     // Convert feet to metres
        m.Groups[2].Success ? float.Parse(m.Groups[1].Value) * 0.0254 : 0     // Convert inches to metres.
    ).ToString());
}



What is says is:


  • Find all occurrences of a number followed by an apostrophe.
  • Convert the numerical value to metres.
  • Substitute all occurrences.


First, extract your numbers-ending-in-quote with a regex.
You can then use the Regex.Match overload that takes a MatchEvaluator as teh second parameter to feed each match individually to a function, which returns the new string.

Regex regex = new Regex(@"\d+(?=')");
string replaced = regex.Replace(inputString, new MatchEvaluator(ReplaceMatch));

The ReplaceMatch method would be along the lines of:

private string ReplaceMatch(Match m)
    {
    double feet = double.Parse(m.Value);
    return string.Format("{0:N2}", feet * 0.3048);
    }


You can split them using the Split() method on the string. Split on ' and then loop through the results.

Something like:

foreach (String str in stringVar.Split("'"))
{
  // do your thing
}


这篇关于如何循环字符串并转换其中的数字。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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