Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Custom Strings

 
Kerry Baer
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Anton Shaikin
Ranch Hand
Posts: 65
IntelliJ IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow, never knew that!
 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic