簡體   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