C# String.Format() 和 String.Join() 的 Java 等价物

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/187676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:12:15  来源:igfitidea点击:

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

c#javastring

提问by Omar Kooheji

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

我知道这是一个新手问题,但是在 Java 中是否有 C# 字符串操作的等价物?

Specifically, I'm talking about String.Formatand String.Join.

具体来说,我说的是String.FormatString.Join

采纳答案by Grant Wagner

The Java String object has a formatmethod (as of 1.5), but no joinmethod.

Java String 对象有一个format方法(从 1.5 开始),但没有join方法。

To get a bunch of useful String utility methods not already included you could use org.apache.commons.lang.StringUtils.

要获得一堆尚未包含的有用 String 实用程序方法,您可以使用org.apache.commons.lang.StringUtils

回答by Allain Lalonde

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

字符串格式。至于join,需要自己写:

 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

以上来自http://snippets.dzone.com/posts/show/91

回答by Bill K

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.

我不能像我想的那样使用 Java 5 语法(信不信由你,我最近一直在使用 1.0.x)所以我可能有点生疏,但我确信这个概念是正确的.

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:

编辑补充:字符串追加可能会很慢,但如果您正在处理 GUI 代码或一些短期运行的例程,那么花费 0.005 秒或 0.006 秒真的没有关系,所以如果您有一个名为“joinMe”的集合如果您想将其附加到现有字符串“目标”中,只需将其内联即可:

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.

更重要的是,它易于记忆、简短、快速且非常易读。性能并不总是设计选择的自动赢家。

回答by djb

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

如果您希望将多个字符串连接(连接)为一个,您应该使用 StringBuilder。它比使用要好得多

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

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

与 StringBuffer 相比,性能也略有提升,因为 StringBuilder 不使用同步。

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.

对于像这样的通用实用程序方法,它会(最终)在许多情况下被多次调用,因此您应该使其高效并且不要分配许多瞬态对象。我们分析了许多不同的 Java 应用程序,几乎总能发现字符串连接和 string/char[] 分配占用了大量的时间/内存。

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.

我们的可重用集合 -> 字符串方法首先计算所需结果的大小,然后使用该初始大小创建一个 StringBuilder;这避免了附加字符串时使用的内部 char[] 的不必要的加倍/复制。

回答by djb

StringUtilsis a pretty useful class in the Apache Commons Lang library.

StringUtils是 Apache Commons Lang 库中一个非常有用的类。

回答by Amir Bashir

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

我只会使用字符串连接运算符“+”来连接两个字符串。 s1 += s2;

回答by sgsweb

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();
  }

回答by Noel Yap

Guavacomes with the Joinerclass.

番石榴自带Joiner

import com.google.common.base.Joiner;

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

回答by gavenkoa

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 Collectionisn't supported by JSP, so for tag function I wrote:

CollectionJSP 不支持,所以对于标签功能,我写道:

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 .tldfile:

并放入.tld文件:

<?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:

并在 JSP 文件中使用它作为:

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

回答by Melllvar

TextUtils.joinis available on Android

TextUtils.join在 Android 上可用