java 将 int 数组转换为字符串变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13477751/
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-10-31 12:55:13  来源:igfitidea点击:

Convert int array to string variable

javaarraysstring

提问by Berkan

I have an integer array that keeps binary numbers 0 and 1 in itself. I want to convert my integer array to a string variable in java. How can I do it?

我有一个整数数组,它本身保留二进制数 0 和 1。我想将我的整数数组转换为 java 中的字符串变量。我该怎么做?

回答by Jo?o Silva

int[] arr = new int[] { 1, 0, 1, 0 };
StringBuilder sb = new StringBuilder(arr.length);
for (int i : arr) {
  sb.append(i);
}
String s = sb.toString(); // 1010

If you don't mind having brackets around your string, and your numbers separated by a comma, you can use Arrays.toStringas suggested by others.

如果您不介意在字符串周围使用括号,并且您的数字用逗号分隔,则可以Arrays.toString按照其他人的建议使用。

回答by ShyJ

Probably Arrays.toString(int[])is what you are looking for.

可能Arrays.toString(int[])就是你要找的。

final int[] sample = new int[] {1, 2, 3};
final String arrayStr = Arrays.toString (sample);
System.out.println (arrayStr);

This should print [1, 2, 3].

这应该打印 [1, 2, 3]。

Here is a fiddlefor it.

这是一个小提琴

回答by Alexander Pogrebnyak

This is one way of doing it:

这是一种方法:

String stringVar = java.util.Arrays.toString( intArray );

回答by zapl

You can also do it manually like this

你也可以像这样手动完成

private static String format(int[] array) {
    StringBuilder sb = new StringBuilder();
    boolean needSeparator = false;
    for (int number : array) {
        if (needSeparator) {
            sb.append(", ");
        }
        if (number != 0) {
            sb.append("true");
        } else {
            sb.append("false");
        }
        needSeparator = true;
    }
    return sb.toString();
}

That would be especially useful if you want to use a special format. Above example will produce strings like "true, false, true"

如果您想使用特殊格式,这将特别有用。上面的例子将产生像这样的字符串"true, false, true"

And a fiddle.

还有一把小提琴

Edit: oops, trueshould be != 0, not !=1. Corrected in above code, broken in fiddle

编辑:哎呀,true应该是!= 0,不是!=1。在上面的代码中更正,在小提琴中损坏