c# string character replace

前端 未结 4 1776
一向
一向 2021-01-14 18:04

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

4条回答
  •  旧巷少年郎
    2021-01-14 18:56

    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.

提交回复
热议问题