Removing a character from my stringbuilder [duplic

2020-06-06 20:26发布

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

标签: c# .net vb.net
6条回答
劳资没心,怎么记你
2楼-- · 2020-06-06 20:41

Use:

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

then call

blahh.Remove( searchKey, 1).Insert(searchKey, " and"); or a blank.
查看更多
【Aperson】
3楼-- · 2020-06-06 20:50

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(",");
查看更多
Lonely孤独者°
4楼-- · 2020-06-06 20:51

Try

mstrResult.Remove( mstrResult.Length - 1 - Environment.NewLine.Length
                 , Environment.NewLine.Length);
查看更多
男人必须洒脱
5楼-- · 2020-06-06 20:52

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);
查看更多
Bombasti
6楼-- · 2020-06-06 20:55

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)
查看更多
狗以群分
7楼-- · 2020-06-06 20:57

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.

查看更多
登录 后发表回答