Remove last specific character in a string c#

前端 未结 8 1294
梦谈多话
梦谈多话 2020-12-13 23:16

I use WinForms c#.I have string value like below,

string Something = \"1,5,12,34,\";

I need to remove last comma in a string. So How can i

相关标签:
8条回答
  • 2020-12-13 23:20

    Try string.TrimEnd():

    Something = Something.TrimEnd(',');
    
    0 讨论(0)
  • 2020-12-13 23:22

    When you have spaces at the end. you can use beliow.

    ProcessStr = ProcessStr.Replace(" ", "");
    Emails     = ProcessStr.TrimEnd(';');
    
    0 讨论(0)
  • 2020-12-13 23:26

    King King's answer is of course right. Also Tim Schmelter's comment is also good suggestion in your case.

    But if you want really remove last comma in a string, you should find the index of last comma and remove like;

    string s = "1,5,12,34,12345";
    int index = s.LastIndexOf(',');
    Console.WriteLine(s.Remove(index, 1));
    

    Output will be;

    1,5,12,3412345
    

    Here a demonstration.

    It is too unlikely you want this way but I want to point it. And remember, String.Remove method doesn't remove any character in original string, it returns new string.

    0 讨论(0)
  • 2020-12-13 23:26

    The TrimEnd method takes an input character array and not a string. The code below from Dot Net Perls, shows a more efficient example of how to perform the same functionality as TrimEnd.

    static string TrimTrailingChars(string value)
    {
        int removeLength = 0;
        for (int i = value.Length - 1; i >= 0; i--)
        {
            char let = value[i];
            if (let == '?' || let == '!' || let == '.')
            {
                removeLength++;
            }
            else
            {
                break;
            }
        }
        if (removeLength > 0)
        {
            return value.Substring(0, value.Length - removeLength);
        }
        return value;
    }
    
    0 讨论(0)
  • 2020-12-13 23:26

    Or you can convert it into Char Array first by:

    string Something = "1,5,12,34,";
    char[] SomeGoodThing=Something.ToCharArray[];
    

    Now you have each character indexed:

    SomeGoodThing[0] -> '1'
    SomeGoodThing[1] -> ','
    

    Play around it

    0 讨论(0)
  • 2020-12-13 23:34

    Try string.Remove();

    string str = "1,5,12,34,";
    string removecomma = str.Remove(str.Length-1);
    MessageBox.Show(removecomma);
    
    0 讨论(0)
提交回复
热议问题