这个基本 Java 方法的等效 C# 方法是什么?

发布于 2024-07-13 22:43:50 字数 746 浏览 9 评论 0原文

这里的问题非常简单(更多的是为了确认我的想法,而不是任何事情)...

Java方法: StringBuffer.Delete(start,end);

Java代码:

sb.delete(sb.length()-2, sb.length());  

C#(不确定这是否正确):

StringBuilder sb = new StringBuilder();
....
sb.Remove(sb.Length - 2, sb.Length - (sb.Length - 2));

我不确定的原因是在Java删除方法的文档中。 它说

子字符串从指定位置开始 开始并延伸到字符 索引结束 - 1 或到末尾 StringBuffer如果没有这样的字符 存在

我只是不太确定这句话的end - 1位..以及我是否可能把事情搞砸了。

干杯:)

编辑:呵呵。 我知道它正在从字符串中删除最后 2 个字符,但我保持了转换的精确性,因此我的代码很冗长。 :)

Really simple question here (more to confirm my thoughts, than anything)...

Java method: StringBuffer.Delete(start,end);

Java code:

sb.delete(sb.length()-2, sb.length());  

C# (not sure if this is right):

StringBuilder sb = new StringBuilder();
....
sb.Remove(sb.Length - 2, sb.Length - (sb.Length - 2));

The reason why I'm not sure is in the documentation of the Java delete method. It says

The substring begins at the specified
start and extends to the character at
index end - 1 or to the end of the
StringBuffer if no such character
exists

I'm just not too sure about this end - 1 bit of that quote .. and if I might have fraked things up.

cheers :)

edit: Heh. I knew that it was deleting the last 2 chars from the string, but I was keeping the conversion exact, hence my verbose code. :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

揪着可爱 2024-07-20 22:43:50

要删除最后 2 个字符,请编写:

sb.Remove(sb.Length - 2, 2);

To delete the last 2 characters you'd write:

sb.Remove(sb.Length - 2, 2);
深海里的那抹蓝 2024-07-20 22:43:50

对,那是正确的。 “end - 1”意味着如果您调用delete(2, 8),它将删除索引为2到7的字符,但不会删除索引为8的字符。

因此,您的代码是正确的。 然而,一些数学技能在这里会派上用场,你会看到:

x - (x - 2)
= x - x + 2
= (x - x) + 2
= 0 + 2
= 2

编写代码:

sb.Remove(sb.Length - 2, 2);

做同样事情的另一种方法是:

sb.Length -= 2;

Yes, that is correct. The "end - 1" means that if you call delete(2, 8) it deletes the characters with index 2 through 7, but not the character with index 8.

So, your code is correct. However some math skills would come in handy here, and you would see that:

x - (x - 2)
= x - x + 2
= (x - x) + 2
= 0 + 2
= 2

Making the code:

sb.Remove(sb.Length - 2, 2);

Another way of doing the same thing would be:

sb.Length -= 2;
如此安好 2024-07-20 22:43:50

在 Java 的删除调用中,它删除从 start 到 end-1 的字符。 相反,C# 调用会从开头删除字符串,持续时间取决于您指定的时间。

In the delete call in Java it removes character from start to end-1. The C# call instead removes a string from start for however long you specify.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文