Removing a character from my string editor

I have the following string builder as msrtResult, which is quite long:

mstrResult.Append(rtbResult.Text).Append("})})" + Environment.NewLine) 

How to remove the last "," from mstrResult Now? (it is in the middle of this mstrResult and is not the last character of the whole line, as I add lines to it) I have to do this before adding a new line. Thanks

+27
Apr 18 2018-11-11T00:
source share
6 answers

You can simply reduce the length to shorten the string (C #):

 mstrResult.Length -= 1; 

EDIT:

After you updated your 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); 
+57
Apr 18 2018-11-11T00:
source share

Add the 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 call:

 yourStringBuilder.RemoveLast(","); 
+11
Jan 31 2018-12-12T00:
source share

You can use StringBuilder.Remove() if you know the position of the characters you want to delete.

I would suggest that it would be easier not to add it in the first place.




Your updated question says removing the last comma character. I assume that you want to do this in order to avoid creating a message that looks like this:

My shopping list contains milk, eggs, butter, and fish.

You would collect this in a loop, iterating over an array. You can usually write a loop so that you simply select (for example, using the if statement) so that you don’t add a command when you are in the last iteration of the loop.

+3
Apr 18 2018-11-11T00:
source share

Try

 mstrResult.Remove( mstrResult.Length - 1 - Environment.NewLine.Length , Environment.NewLine.Length); 
+1
Apr 18 2018-11-11T00:
source share

To simply delete the last character you added, use below: (This is VB, but C should work similarly)

 Dim c As New StringBuilder c.Remove(c.Length - 1, 1) 
0
Nov 16 '16 at 20:37
source share

Using:

 stringbuilder blahh = new stringbuilder() int searchKey = blahh.LastIndexOf(','); 

then call

 blahh.Remove( searchKey, 1).Insert(searchKey, " and"); or a blank. 
-2
Sep 12 '14 at 15:43
source share



All Articles