简体   繁体   English

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

[英]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? 我知道这是一个新手问题,但在Java中C#的字符串操作是否相同?

Specifically, I'm talking about String.Format and String.Join . 具体来说,我在谈论String.FormatString.Join

The Java String object has a format method (as of 1.5), but no join method. 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

String.format . 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 以上内容来自http://snippets.dzone.com/posts/show/91

Guava comes with the Joiner class . Guava配有Joiner课程

import com.google.common.base.Joiner;

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

As of Java 8, join() is now available as two class methods on the String class. 从Java 8开始, join()现在可以作为String类的两个类方法使用。 In both cases the first argument is the delimiter. 在这两种情况下,第一个参数是分隔符。

You can pass individual CharSequence s as additional arguments : 您可以将单个CharSequence作为附加参数传递

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

Or you can pass an Iterable<? extends CharSequence> 或者你可以传递一个Iterable<? extends CharSequence> Iterable<? extends CharSequence> : 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: Java 8还添加了一个新类StringJoiner ,您可以像这样使用它:

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"

TextUtils.join可在Android上使用

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

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代码或一些短时间运行例程,那么如果您使用.005秒或.006则无关紧要,因此如果您有一个名为“joinMe”的集合你想要附加到现有的字符串“target”,只是内联这个并不可怕:

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. 性能并不总是设计选择的自动赢家。

Here is a pretty simple answer. 这是一个非常简单的答案。 Use += since it is less code and let the optimizer convert it to a StringBuilder for you. 使用+=因为代码较少,让优化器为您将其转换为StringBuilder 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();
        }

I didn't want to import an entire Apache library to add a simple join function, so here's my hack. 我不想导入整个Apache库来添加一个简单的连接函数,所以这是我的黑客。

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

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: 但是JSP不支持Collection ,所以对于tag函数我写道:

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: 并放入.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, ", ")}

If you wish to join (concatenate) several strings into one, you should use a StringBuilder. 如果您希望将多个字符串连接(连接)为一个字符串,则应使用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. 由于StringBuilder不使用同步,因此对StringBuffer的性能略有提升。

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应用程序,并且几乎总是发现字符串连接和字符串/ char []分配占用了大量的时间/内存。

Our reusable collection -> string method first calculates the size of the required result and then creates a StringBuilder with that initial size; 我们的可重用集合 - > string方法首先计算所需结果的大小,然后创建一个具有该初始大小的StringBuilder; this avoids unecessary doubling/copying of the internal char[] used when appending strings. 这避免了在附加字符串时使用的内部char []的不必要的加倍/复制。

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

MessageFormat.format()就像C#的String.Format()

I see a lot of overly complex implementations of String.Join here. 我在这里看到很多过于复杂的String.Join实现。 If you don't have Java 1.8, and you don't want to import a new library the below implementation should suffice. 如果您没有Java 1.8,并且您不想导入新库,则以下实现应该足够了。

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();
}
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. 基本上,String ntop使用逗号分隔符和括号存储整个集合的值。

I would just use the string concatenation operator "+" to join two strings. 我只想使用字符串连接运算符“+”来连接两个字符串。 s1 += s2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM