我有一个字符串,其中倒数第三个字符有时是
编辑:感谢大家的答案。只是为了澄清,是的,我指的是形式为
,
。如果是这种情况,我想用 .
替换它。该字符串可能还有其他的 ,
。是否有一种优雅的解决方案?编辑:感谢大家的答案。只是为了澄清,是的,我指的是形式为
xxxxxx,xx
的字符串(这是欧洲货币问题)。if (text[text.Length - 3] == ',')
{
StringBuilder builder = new StringBuilder(text);
builder[text.Length - 3] = '.';
text = builder.ToString();
}
编辑:我希望上面的方法是最有效的。你可以尝试使用字符数组代替:
if (text[text.Length - 3] == ',')
{
char[] chars = text.ToCharArray();
chars[text.Length - 3] = '.';
text = new string(chars);
}
使用Substring
也可以,但我认为它并没有更易读:
if (text[text.Length - 3] == ',')
{
text = text.Substring(0, text.Length - 3) + "."
+ text.Substring(text.Length - 2);
}
编辑:在这种情况下,我一直假设您已经知道文本长度至少为三个字符。如果不是这样的话,您显然也需要进行测试。
string text = "Hello, World,__";
if (text.Length >= 3 && text[text.Length - 3] == ',')
{
text = text.Substring(0, text.Length - 3) + "." + text.Substring(text.Length - 2);
}
// text == "Hello, World.__"
更为恰当的方法可能是使用文化(cultures)
string input = "12345,67";
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL");
decimal value = System.Convert.ToDecimal(input);
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
string converted = string.Format("{0:C}", value);
试试这个
System.Text.RegularExpressions.Regex.Replace([the_string], "(,)(.{2})$", ".$2")
RegexOptions.Singleline
枚举作为额外参数。static readonly Regex _rxReplace = new Regex("(,)(.{2})$", RegexOptions.Compiled);
然后当你想要使用它时,只需要:
var fixed = _rxReplace.Replace([the_string], ".$2");
string.Format("{0:0.00}", 275.95, System.Globalization.CultureInfo.CreateSpecificCulture("nl-BE"));
不是更清晰吗?此示例将返回 275,95。 - Peter