从使用stringbuilder构建的字符串中删除最后一个字符的最佳方法 [英] Best way to remove the last character from a string built with stringbuilder

查看:311
本文介绍了从使用stringbuilder构建的字符串中删除最后一个字符的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下

data.AppendFormat("{0},",dataToAppend);

这个问题是我在循环中使用它,并且会有一个试验逗号.删除尾部逗号的最佳方法是什么?

The problem with this is that I am using it in a loop and there will be a trialling comma. What is the best way to remove the trailing comma?

我是否必须将数据更改为字符串的子字符串呢?

Do I have to change data to a string the substring it?

推荐答案

最简单,最有效的方法是执行以下命令:

The simplest and most efficient way is to perform this command:

data.Length--;

通过执行此操作,可以将指针(即最后一个索引)移回一个字符,但不会更改对象的可变性.实际上,清除 StringBuilder 最好也用 Length 完成(但实际上为了清楚起见,实际上使用了 Clear()方法,因为那是原因)它的实现看起来像):

by doing this you move the pointer (i.e. last index) back one character but you don't change the mutability of the object. In fact, clearing a StringBuilder is best done with Length as well (but do actually use the Clear() method for clarity instead because that's what its implementation looks like):

data.Length = 0;

再次

,因为它不会更改分配表.想起来就像是说,我不想再识别这些字节了.现在,即使调用 ToString(),它也无法识别超过其 Length 的任何内容,但是,它无法识别.这是一个可变的对象,它分配的空间比您提供的空间要多,它只是通过这种方式构建的.

again, because it doesn't change the allocation table. Think of it like saying, I don't want to recognize these bytes anymore. Now, even when calling ToString(), it won't recognize anything past its Length, well, it can't. It's a mutable object that allocates more space than what you provide it, it's simply built this way.

这篇关于从使用stringbuilder构建的字符串中删除最后一个字符的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆