This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Custom Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Custom Strings" Watch "Custom Strings" New topic
Author

Custom Strings

Kerry Baer
Ranch Hand

Joined: Jun 23, 2010
Posts: 39
I want to do something similar to what PreparedStatement does. I want to have a string that looks like this:


Now I want to insert the appropriate values in for each question mark. I don't want to use charAt() and replace.

In ASP.NET there is a function where you do this:


Any help with this is appreciated.

Thanks
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19914
    
  23

Since Java 5.0 you can use the java.util.Formatter way:
This has two drawbacks: the order is very important, and if you need the same value in multiple places you need to provide them multiple times.

MessageFormat can help you with that:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Anton Shaykin
Ranch Hand

Joined: Dec 13, 2009
Posts: 57

Rob Prime wrote:This has two drawbacks: the order is very important, and if you need the same value in multiple places you need to provide them multiple times.

Nope, you're wrong here. Argument indexes could be used like this:

which would result in:

Also you can use "<" to reference previously referenced element like this:

The output would be:
>
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19914
    
  23

Wow, never knew that!
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 19351
    
  10

And MessageFormat allows you to customize the base string like this:

I wouldn't be surprised to find out that String.format allows you to do the same sort of thing, though.
Kerry Baer
Ranch Hand

Joined: Jun 23, 2010
Posts: 39
Thanks for the help!
 
I agree. Here's the link: http://kickstarter.com/rocket-mass-heater
 
subject: Custom Strings