c#字符串字符替换

时间:2011-08-08 13:45:04

标签: c# string

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

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

4 个答案:

答案 0 :(得分:7)

怎么样:

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

编辑:我一直在假设在这种情况下你已经知道文本的长度至少为三个字符。如果情况并非如此,那么您显然也希望对此进行测试。

答案 1 :(得分:4)

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

答案 2 :(得分:2)

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

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

答案 3 :(得分:1)

试试这个

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");
相关问题