Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a character from my stringbuilder [duplicate]

Tags:

c#

.net

vb.net

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

like image 740
Faulty Orc Avatar asked Apr 18 '11 09:04

Faulty Orc


People also ask

How do I delete a character in StringBuilder?

In order to remove a substring from a Java StringBuilder Object, we use the delete() method. The delete() method removes characters in a range from the sequence. The delete() method has two parameters, start, and end. Characters are removed from start to end-1 index.

How remove duplicates from StringBuilder in Java?

We can remove the duplicate characters from a string by using the simple for loop, sorting, hashing, and IndexOf() method.

How do I remove the last two characters from a StringBuilder in Java?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove. Remove last character of a string using sb.


2 Answers

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); 
like image 156
Kristoffer Lindvall Avatar answered Oct 12 '22 23:10

Kristoffer Lindvall


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(","); 
like image 32
Md Nazmoon Noor Avatar answered Oct 12 '22 23:10

Md Nazmoon Noor