C#中的字符串字符替换 [英] c# string character replace

查看:109
本文介绍了C#中的字符串字符替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,其中倒数第三的性格有时是如果这是我想用来替换它的情况。的字符串也可能有其他的的各处。是否有一个优雅的解决方案呢?

I have a string where the third last character is sometimes a , If this is the case I want to replace it with a . The string could also have other ,'s throughout. Is there an elegant solution to this?

编辑:谢谢大家对你的答案。只是为了澄清,是由倒数第三我指的是格式的字符串 XXXXXX,XX (这是一个欧洲货币东西)

Thanks everyone for your answers. Just to clarify, yes by third last I mean a string of the form xxxxxx,xx (it's a european currency thing)

推荐答案

如何:

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



编辑:我的希望的上面是差不多最有效的方法。你可以尝试使用一个字符数组来代替:

I hope the above is just about the most efficient approach. You could try using a char array instead:

if (text[text.Length - 3] == ',')
{
    char[] chars = text.ToCharArray();
    chars[text.Length - 3] = '.';
    text = new string(chars);
}

使用子串将工作为好,但我不认为这是任何更具可读性:

Using Substring will work as well, but I don't think it's any more readable:

if (text[text.Length - 3] == ',')
{
    text = text.Substring(0, text.Length - 3) + "."
           + text.Substring(text.Length - 2);
}



编辑:我一直假设在这种情况下,你已经知道文将至少三个字符长度。如果不是这种情况,你显然希望为该以及测试。

I've been assuming that in this situation you already know that text will be at least three characters length. If that's not the case, you'd obviously want a test for that as well.

这篇关于C#中的字符串字符替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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