This question already has answers here:
Closed last year.
I am having the following string builder as msrtResult, which is quite long:
mstrResult.Append(rtbResult.Text).Append("})})" + Environment.NewLine)
How can I remove the last "," from mstrResult Now? (it is in the middle of that mstrResult and it is not the last character of the whole string since I am appending strings to it)
I should do it before adding the newline.
Thanks
You can just decrease the length to shorten the string (C#):
mstrResult.Length -= 1;
EDIT:
After you updated you question, I think I know what you want :) How about this:
mstrResult.Append(rtbResult.Text).Append("})})" + Environment.NewLine);
var index = mstrResult.ToString().LastIndexOf(',');
if (index >= 0)
mstrResult.Remove(index, 1);
Add a StringBuilder extension.
public static StringBuilder RemoveLast(this StringBuilder sb, string value)
{
if(sb.Length < 1) return sb;
sb.Remove(sb.ToString().LastIndexOf(value), value.Length);
return sb;
}
then invoke:
yourStringBuilder.RemoveLast(",");
You can use StringBuilder.Remove()
if you know the position of the character(s) you want to remove.
I'd imagine that it would be easier not to add it in the first place.
Your updated question talks about removing the last comma character. I'm guessing you want to do this to avoid creating a message that looks like this:
My shopping list contained milk, eggs,
butter, and fish.
You'd assemble this in a loop, iterating over an array. Usually you can write the loop so that you simply choose (e.g. with an if statement) not to add the command when you are in the final iteration of the loop.
To just remove the last character you appended use below: (This is VB but C should work similarly)
Dim c As New StringBuilder
c.Remove(c.Length - 1, 1)
Try
mstrResult.Remove( mstrResult.Length - 1 - Environment.NewLine.Length
, Environment.NewLine.Length);
Use:
stringbuilder blahh = new stringbuilder()
int searchKey = blahh.LastIndexOf(',');
then call
blahh.Remove( searchKey, 1).Insert(searchKey, " and"); or a blank.