Remove Last Character of String createobject("java", "java.lang.StringBuffer").init()

Manipulating strings which are Java objects created in ColdFusion is a lot different that using standard CF functions. Once the Java object is created, Java methods must be used to manipulate the object.

How do I remove the last character of a Java object string created using the StringBuffer class?

view plain print about
1<cfset myString = createobject("java", "java.lang.StringBuffer").init() />

Here is a listing of the methods that can be used:

http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html

The most common method seen used in CF is the append() method.

view plain print about
1<cfset myString.append("more string text" & thisVariable & " to " & thatVariable & "!")/>

demonstrates some string concatenation. Notice that there is an exclamation point (!) added to the end.

So the boss says, "No more exclamation points!!! Just at the end, you can use them in the middle of strings, like when I call you a @&!!*#% you worthless @#$%#!!"

So, before you start looking for another job (who could work for someone who talks to you like that?), we will remove the exclamation point at the end. The obvious way to do this would be just remove the concatenated

view plain print about
1& "!"

But the point of this lesson is to remove it using a Java StringBuffer method.

We could use deleteCharAt(), that's a StringBuffer method, but how do we find what the index of the exclamation point is?. It's at the end of a varying length string, changing every time the function is called and new variables are introduced.

This is where another StringBuffer method, length() comes to play

view plain print about
1<cfset myString.deleteCharAt(myString.length()-1) />

Starting from the inside, we find the myString length, subtract one and delete the character in that position.

This is a simple example but it is just for demonstration. On this post you can see how it came in really handy.

Related Blog Entries

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.9.7. Contact Blog Owner