Java equivalents of C# String.Format() and String.Join()

I know this is a bit of a newbie question, but are there equivalents to C#'s string operations in Java?

Specifically, I'm talking about String.Format and String.Join.


Asked by: Edgar572 | Posted: 21-01-2022






Answer 1

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.

Answered by: Cherry339 | Posted: 22-02-2022



Answer 2

String.format. As for join, you need to write your own:

 static String join(Collection<?> s, String delimiter) {
     StringBuilder builder = new StringBuilder();
     Iterator<?> iter = s.iterator();
     while (iter.hasNext()) {
         builder.append(iter.next());
         if (!iter.hasNext()) {
           break;                  
         }
         builder.append(delimiter);
     }
     return builder.toString();
 }

The above comes from http://snippets.dzone.com/posts/show/91

Answered by: Blake431 | Posted: 22-02-2022



Answer 3

Guava comes with the Joiner class.

import com.google.common.base.Joiner;

Joiner.on(separator).join(data);

Answered by: Michelle770 | Posted: 22-02-2022



Answer 4

As of Java 8, join() is now available as two class methods on the String class. In both cases the first argument is the delimiter.

You can pass individual CharSequences as additional arguments:

String joined = String.join(", ", "Antimony", "Arsenic", "Aluminum", "Selenium");
// "Antimony, Arsenic, Alumninum, Selenium"

Or you can pass an Iterable<? extends CharSequence>:

List<String> strings = new LinkedList<String>();
strings.add("EX");
strings.add("TER");
strings.add("MIN");
strings.add("ATE");

String joined = String.join("-", strings);
// "EX-TER-MIN-ATE"

Java 8 also adds a new class, StringJoiner, which you can use like this:

StringJoiner joiner = new StringJoiner("&");
joiner.add("x=9");
joiner.add("y=5667.7");
joiner.add("z=-33.0");

String joined = joiner.toString();
// "x=9&y=5667.7&z=-33.0"

Answered by: Aston260 | Posted: 22-02-2022



Answer 5

TextUtils.join is available on Android

Answered by: Ada851 | Posted: 22-02-2022



Answer 6

You can also use variable arguments for strings as follows:

  String join (String delim, String ... data) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < data.length; i++) {
      sb.append(data[i]);
      if (i >= data.length-1) {break;}
      sb.append(delim);
    }
    return sb.toString();
  }

Answered by: Lucas177 | Posted: 22-02-2022



Answer 7

As for join, I believe this might look a little less complicated:

public String join (Collection<String> c) {
    StringBuilder sb=new StringBuilder();
    for(String s: c)
        sb.append(s);
    return sb.toString();
}

I don't get to use Java 5 syntax as much as I'd like (Believe it or not, I've been using 1.0.x lately) so I may be a bit rusty, but I'm sure the concept is correct.

edit addition: String appends can be slowish, but if you are working on GUI code or some short-running routine, it really doesn't matter if you take .005 seconds or .006, so if you had a collection called "joinMe" that you want to append to an existing string "target" it wouldn't be horrific to just inline this:

for(String s : joinMe)
    target += s;

It's quite inefficient (and a bad habit), but not anything you will be able to perceive unless there are either thousands of strings or this is inside a huge loop or your code is really performance critical.

More importantly, it's easy to remember, short, quick and very readable. Performance isn't always the automatic winner in design choices.

Answered by: Rubie685 | Posted: 22-02-2022



Answer 8

Here is a pretty simple answer. Use += since it is less code and let the optimizer convert it to a StringBuilder for you. Using this method, you don't have to do any "is last" checks in your loop (performance improvement) and you don't have to worry about stripping off any delimiters at the end.

        Iterator<String> iter = args.iterator();
        output += iter.hasNext() ? iter.next() : "";
        while (iter.hasNext()) {
            output += "," + iter.next();
        }

Answered by: Melissa996 | Posted: 22-02-2022



Answer 9

I didn't want to import an entire Apache library to add a simple join function, so here's my hack.

    public String join(String delim, List<String> destinations) {
        StringBuilder sb = new StringBuilder();
        int delimLength = delim.length();

        for (String s: destinations) {
            sb.append(s);
            sb.append(delim);
        }

        // we have appended the delimiter to the end 
        // in the previous for-loop. Let's now remove it.
        if (sb.length() >= delimLength) {
            return sb.substring(0, sb.length() - delimLength);
        } else {
            return sb.toString();
        }
    }

Answered by: Anna562 | Posted: 22-02-2022



Answer 10

If you wish to join (concatenate) several strings into one, you should use a StringBuilder. It is far better than using

for(String s : joinMe)
    target += s;

There is also a slight performance win over StringBuffer, since StringBuilder does not use synchronization.

For a general purpose utility method like this, it will (eventually) be called many times in many situations, so you should make it efficient and not allocate many transient objects. We've profiled many, many different Java apps and almost always find that string concatenation and string/char[] allocations take up a significant amount of time/memory.

Our reusable collection -> string method first calculates the size of the required result and then creates a StringBuilder with that initial size; this avoids unecessary doubling/copying of the internal char[] used when appending strings.

Answered by: Maddie203 | Posted: 22-02-2022



Answer 11

I wrote own:

public static String join(Collection<String> col, String delim) {
    StringBuilder sb = new StringBuilder();
    Iterator<String> iter = col.iterator();
    if (iter.hasNext())
        sb.append(iter.next().toString());
    while (iter.hasNext()) {
        sb.append(delim);
        sb.append(iter.next().toString());
    }
    return sb.toString();
}

but Collection isn't supported by JSP, so for tag function I wrote:

public static String join(List<?> list, String delim) {
    int len = list.size();
    if (len == 0)
        return "";
    StringBuilder sb = new StringBuilder(list.get(0).toString());
    for (int i = 1; i < len; i++) {
        sb.append(delim);
        sb.append(list.get(i).toString());
    }
    return sb.toString();
}

and put to .tld file:

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
    <function>
        <name>join</name>
        <function-class>com.core.util.ReportUtil</function-class>
        <function-signature>java.lang.String join(java.util.List, java.lang.String)</function-signature>
    </function>
</taglib>

and use it in JSP files as:

<%@taglib prefix="funnyFmt" uri="tag:com.core.util,2013:funnyFmt"%>
${funnyFmt:join(books, ", ")}

Answered by: Catherine335 | Posted: 22-02-2022



Answer 12

StringUtils is a pretty useful class in the Apache Commons Lang library.

Answered by: Emily416 | Posted: 22-02-2022



Answer 13

There is MessageFormat.format() which works like C#'s String.Format().

Answered by: Melissa699 | Posted: 22-02-2022



Answer 14

I see a lot of overly complex implementations of String.Join here. If you don't have Java 1.8, and you don't want to import a new library the below implementation should suffice.

public String join(Collection<String> col, String delim) {
    StringBuilder sb = new StringBuilder();
    for ( String s : col ) {
        if ( sb.length() != 0 ) sb.append(delim);
        sb.append(s);
    }
    return sb.toString();
}

Answered by: Oliver343 | Posted: 22-02-2022



Answer 15

ArrayList<Double> j=new ArrayList<>; 
j.add(1);
j.add(.92);
j.add(3); 
String ntop=j.toString(); //ntop= "[1, 0.92, 3]" 

So basically, the String ntop stores the value of the entire collection with comma separators and brackets.

Answered by: Vanessa201 | Posted: 22-02-2022



Answer 16

I would just use the string concatenation operator "+" to join two strings. s1 += s2;

Answered by: Ned868 | Posted: 22-02-2022



Similar questions

Should I use Java's String.format() if performance is important?

We have to build Strings all the time for log output and so on. Over the JDK versions we have learned when to use StringBuffer (many appends, thread safe) and StringBuilder (many appends, non-thread-safe). What's the advice on using String.format()? Is it efficient, or are we forced to stick with concatenation for one-liners where performance is important? e.g. ugly ol...


java - print spaces with String.format()

how I can rewrite this: for (int i = 0; i &lt; numberOfSpaces; i++) { System.out.print(" "); } using String.format()? PS I'm pretty sure that this is possible but the javadoc is a bit confusing.


java - String.format()

"%11.2lf" of C++ is equivalent to ? You guys have any resource that shows the equivalent formats for both Java and C++?


C++ Equivalent of %ld in Java for String.format()

For instance, %11.2lf in C++ becomes %11.2f in Java. How about for long format?


java - String.format() to fill a string?

I need to fill a String to a certain length with dashes, like: cow-----8 cow-----9 cow----10 ... cow---100 the total length of the string needs to be 9. The prefix "cow" is constant. I'm iterating up to an input number. I can do this in an ugly way: String str = "cow"; for (int i = 0; i &lt; 1000; i++) { if (i &lt; 10) { str += "-----"; } else if (i &lt...


java - Using String.format() as annotation attribute value

I have a class that have a number of constants: public class SecurityConstants { private static final String HAS_ROLE_TEMPLATE = "hasRole('%s')"; public static final String ROLE_USER_INTERNAL = "ROLE_USER_INTERNAL"; public static final String HAS_ROLE_USER_INTERNAL = String.format(HAS_ROLE_TEMPLATE, ROLE_USER_INTERNAL); } If I then try to use HAS_ROLE_USER_INTERNAL


In Java, is the immutability of Strings considered in the implementation of String.format()?

Since Strings in Java are immutable, I've always used StringBuilder or StringBuffer to concatenate Strings. Does the String.format() method handle this issue as well as StringBuilder or StringBuffer? In other words, does String.format() manage memory as well as StringBuffer or StringBuilder?


Java String.Format() specifier 's' - strange behaviour

I have following code: String requestString=String.format(Constants.SEARCH_SETS_API, Constants.DEVELOPER_KEY, "ids:".concat(setId), "1"); where public static final String DEVELOPER_KEY = "3ansrfnt10cggo80"; public static final String SEARCH_SETS_API = ...


An issue occur when compiled source code with java 1.6 and run on 1.3 with String.Format() Exception

Compiled String.format("%,.2f", new Object[]{new Double(tranInfo.getAmount())}); -> tranInfo.getAmount() return double and got an exception alert when run on java 1.3 on Sco OpenServer OS : java.lang.NoSuchMethodError at FileChangeNotification.displayMessage(FileChangeNotification.java:84) at FileChangeNotification.processMessage(Fi...


java - Error with String.format()

Below is simple code, I got java.util.IllegalFormatConversionException whenever i == 0. java.util.Random r = new java.util.Random(); int i = r.nextInt(2); String s = String.format( String.format("%s", i == 0 ? "%d" : "%f"), i == 0 ? r.nextInt() : r.nextFloat()); System.out.println(s); The stack trace: Exception in thread "main" java.util.Il...






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top