繁体   English   中英

c#字符串字符替换

[英]c# string character replace

我有一个字符串,其中第三个最后一个字符有时是a ,如果是这种情况我想用一个替换它. 该字符串还可能有其他的,的贯穿始终。 有一个优雅的解决方案吗?

编辑:谢谢大家的答案。 只是为了澄清,是的,到第三位,我的意思是一个xxxxxx,xx形式的字符串xxxxxx,xx (这是一个欧洲货币的东西)

怎么样:

if (text[text.Length - 3] == ',')
{
    StringBuilder builder = new StringBuilder(text);
    builder[text.Length - 3] = '.';
    text = builder.ToString();
}

编辑:我希望以上只是最有效的方法。 您可以尝试使用char数组:

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.__"

更合适的方法可能是使用文化

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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM