tags:

views:

150

answers:

2

How can i remove just first comma + space from below if its there else do nothing.

string comments = ", 38, ";
+5  A: 
if( comments.StartsWith(", ") && comments.Length > 2 ) {
  comments = comments.Substring(2);
}
Zachary Yates
This will fail if the string is only ", ", since position 3 does not exist.
Mystere Man
And will also give the wrong result if the string starts with just a comma or a space. ",38, " will turn into "8,".
Paw Baltzersen
@Paw I don't think so, since ",38, " does not start with ", "
Zachary Yates
@Mystere Added a check for length based on your comment.
Zachary Yates
+3  A: 

The best way would be to use the String.TrimStart(...) method.

string comments = ", 38, ";
string commentsOK = "38, ";

string trimmedComments = comments.TrimStart(',', ' ');
string trimmedCommentsOK = commentsOK.TrimStart(',', ' ');

After this both trimmedComments and trimmedCommentsOK would have the value "38, ".

String.TrimStart method reference: http://msdn.microsoft.com/en-us/library/system.string.trimstart.aspx

Aydsman
I learned something new today.
recursive
Wouldn't that also remove " ," from " ,38, "? The TrimStart method is designed to remove all leading chars specified in the arguments, regardless of their order. Based on the question I think you're incorrectly applying TrimStart.
Zachary Yates
Aydsman