views:

336

answers:

3

Hi folks,

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

Java method : [StringBuffer.Delete]1;

[1]: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html#delete(int, int)

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, hencse my verbose code. :)

+1  A: 

To delete the last 2 characters you'd write:

sb.Remove(sb.Length - 2, 2);
Jess
A: 

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.

Jon
A: 

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;
Guffa
why the downvote?
Andrew Bullock