简体   繁体   English

c#字符串字符替换

[英]c# string character replace

I have a string where the third last character is sometimes a , If this is the case I want to replace it with a . 我有一个字符串,其中第三个最后一个字符有时是a ,如果是这种情况我想用一个替换它. The string could also have other , 's throughout. 该字符串还可能有其他的,的贯穿始终。 Is there an elegant solution to this? 有一个优雅的解决方案吗?

EDIT: 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) 只是为了澄清,是的,到第三位,我的意思是一个xxxxxx,xx形式的字符串xxxxxx,xx (这是一个欧洲货币的东西)

How about: 怎么样:

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

EDIT: I hope the above is just about the most efficient approach. 编辑:我希望以上只是最有效的方法。 You could try using a char array instead: 您可以尝试使用char数组:

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: 使用Substring也可以,但我认为它不再具有可读性:

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

EDIT: 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. 如果不是这样的话,你显然也想要对它进行测试。

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

A more proper method would probably be to use the 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);

Try this 尝试这个

System.Text.RegularExpressions.Regex.Replace([the_string], "(,)(.{2})$", ".$2")

It should do it if by 'third last character' you literally mean the third-last character in the whole string. 它应该这样做,如果通过'第三个最后一个字符',你的字面意思是整个字符串中的倒数第三个字符。

That said - you might need to tweak if there are new lines - eg add the RegexOptions.Singleline enum as an extra parameter. 也就是说 - 如果有新行,您可能需要进行调整 - 例如,将RegexOptions.Singleline枚举添加为额外参数。

For better performance - probably - you could pre-declare the regex inside a class body: 为了获得更好的性能 - 可能 - 你可以在类体中预先声明正则表达式:

static readonly Regex _rxReplace = new Regex("(,)(.{2})$", RegexOptions.Compiled);

Then when you want to use it it's just: 然后,当你想使用它时,它只是:

var fixed = _rxReplace.Replace([the_string], ".$2");

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

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