c# string character replace

2020-03-26 07:14发布

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?

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)

标签: c# string
4条回答
地球回转人心会变
2楼-- · 2020-03-26 07:51

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 - e.g. add the RegexOptions.Singleline enum as an extra parameter.

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");
查看更多
别忘想泡老子
3楼-- · 2020-03-26 08:04

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);
查看更多
Anthone
4楼-- · 2020-03-26 08:05

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:

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

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.

查看更多
家丑人穷心不美
5楼-- · 2020-03-26 08:06
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.__"
查看更多
登录 后发表回答