It's not a secret anymore!*
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


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: 19697
    
  20

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: 19697
    
  20

Wow, never knew that!
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18570
    
    8

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://aspose.com/file-tools
 
subject: Custom Strings