Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove "," from string if present at end [closed]

Tags:

c#

asp.net

What is the best way to remove , from following strings.

  1. one,two,three,
  2. three,four,five
  3. six,seven,eight,nine,ten,

    int strLength = someString.Length;
    
    if (strLength > 0)
    {
         findString = findString .Substring(0, str.Length - 1);
    }
    
    if (findString ==",")
    {
         someString.Remove(someString.Length - 1)
    }
    

I have quickly compiled this code directly in StackExchange editor as an example (It may be have syntax error.

Please take above as logic purpose only.

I would appreciate if someone can provide optimized code for above logic.

UPDATE: I actually want to remove , from string if present at the end of string not in middle.

like image 371
Learning Avatar asked Apr 08 '13 12:04

Learning


2 Answers

How about this.

yourString = yourString.TrimEnd(',');
like image 162
Dilshod Avatar answered Oct 04 '22 21:10

Dilshod


A one line option:

someString = someString.EndsWith(",") ? someString.Substring(0, someString.Length - 1) : someString;

EDIT:

As per Dilshod's answer, this can be expressed as

someString = someString.TrimEnd(',');

which, IMHO, is better.

like image 32
Andrew Grothe Avatar answered Oct 04 '22 20:10

Andrew Grothe