Java equivalents of C# String.Format() and String.Join()
The Java String object has a format
method (as of 1.5), but no join
method.
To get a bunch of useful String utility methods not already included you could use org.apache.commons.lang.StringUtils.
String.Format (.NET) equivalent in Java?
The other suggestions are certainly good, but are more in the style of printf
and its lineage which are more recent additions to Java. The code you posted looks to be inspired by MessageFormat
.
String format = "Test: {0}, {1}"
System.out.println(MessageFormat.format(format, "Text1", "Text2"))
I'm not really certain about what the 'Return:
statement is doing though.
Java: convert ListString to a join()d String
String.join
With Java 8 you can do this without any third party library.
If you want to join a Collection of Strings you can use the String.join
() method:
List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"
Collectors.joining
If you have a Collection with another type than String you can use the Stream API with the joining Collector:
List<Person> list = Arrays.asList(
new Person("John", "Smith"),
new Person("Anna", "Martinez"),
new Person("Paul", "Watson ")
);
String joinedFirstNames = list.stream()
.map(Person::getFirstName)
.collect(Collectors.joining(", ")); // "John, Anna, Paul"
The StringJoiner
class may also be useful.
String Array to String
String[] start = {"first", "second", "third"};
String addedTogether = Arrays.toString(start);
System.out.println(addedTogether);
//prints [first, second, third]
delimeter in String.Join()
It works, but the String is immutable. The method replaceAll(..) returns the new String itself with replacement and you need to assign it to a variable.
String helper = "a,b";
String temp = "','";
helper = helper.replaceAll(",",temp);
Fastest way to put contents of SetString to a single String with words separated by a whitespace?
With commons/lang you can do this using StringUtils.join:
String str_1 = StringUtils.join(set_1, " ");
You can't really beat that for brevity.
Update:
Re-reading this answer, I would prefer the other answer regarding Guava's Joiner now. In fact, these days I don't go near apache commons.
Another Update:
Java 8 introduced the method String.join()
String joined = String.join(",", set);
While this isn't as flexible as the Guava version, it's handy when you don't have the Guava library on your classpath.
unexpected String.join() behavior
You're iterating over the list, and calling String.join
with a single entry each time. That's never going to use the delimiter.
To make this clear, consider these two examples:
String x1 = String.join(",", "a");
String x2 = String.join(",", "a", "b");
Then the value of x1
will be "a", and the value of x2
will be "a,b". String.join
only adds the delimiter between items - so if you only pass it a single item, it doesn't need to add any delimiters.
You can just remove your for
loop, and replace it with:
System.out.println(String.join(",", str));
String.Format vs ToString()
I did a little benchmark in Linqpad:
void Main()
{
int iterations = 1000000;
decimal d = 12.0m;
var text = "";
var sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
// 1. how I'd have done it
text = d.ToString();
}
sw.Stop();
sw.ElapsedMilliseconds.Dump("ToString()");
sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
// 2. how I saw someone do it today
text = String.Format("{0}", d);
}
sw.Stop();
sw.ElapsedMilliseconds.Dump("Format");
}
ToString()
157
Format
264
ToString() looks consistently faster.
EDIT: I should point out, that on my PC 10 million "Format" operations only took 2.2 seconds. This looks very much like a micro-optimization, and unless what you're doing is extremely performance-critical, or iterative - it'd not worry about this too much.
Related Topics
Getting All File Names from a Folder Using C#
Dynamically Setting CSS Values Using ASP.NET
Operators as Method Parameters in C#
C# Version of Java's Synchronized Keyword
Closing Excel Application Process in C# After Data Access
MVC Which Submit Button Has Been Pressed
How to Make My Product as a Trial Version for 30 Days
Determine the File Type Using C#
Query an Xdocument for Elements by Name at Any Depth
What Is the Purpose of Anonymous { } Blocks in C Style Languages
Set Gridview Backcolor to Color from Datatable
How to Pass Constructor Parameters to Unity's Resolve() Method