Best way to convert an array of integers to a string in Java

隐身守侯 提交于 2020-07-05 04:42:27

问题


In Java, I have an array of integers. Is there a quick way to convert them to a string?

I.E. int[] x = new int[] {3,4,5} x toString() should yield "345"


回答1:


Simplest performant approach is probably StringBuilder:

StringBuilder builder = new StringBuilder();
for (int i : array) {
  builder.append(i);
}
String text = builder.toString();

If you find yourself doing this in multiple places, you might want to look at Guava's Joiner class - although I don't believe you'll be able to use it for primitive arrays. EDIT: As pointed out below, you can use Ints.join for this.




回答2:


   int[] x = new int[] {3,4,5};
   String s = java.util.Arrays.toString(x).replaceAll("[\\,\\[\\]\\ ]", "")

Update

For completeness the Java 8 Streams solution, but it isn't pretty (libraries like vavr would be shorter and faster):

String s = IntStream.of(x)
  .mapToObj(Integer::toString)
  .collect(Collectors.joining(""));



回答3:


Try with this - you have to import java.util.Arrays and then -

String temp = Arrays.toString( intArray ).replace(", ", "");
String finalStr = temp.substring(1, temp.length()-2);

Where intArray is your integer array.




回答4:


StringBuffer str =new StringBuffer();
for(int i:x){  
str.append(i);
}  

You need to read all once at least.




回答5:


public static void main(String[] args) {
    int[] dice = {1, 2, 3, 4, 5, 0};
    String string = "";

    for (int i = 0; i < dice.length; i++) {
        string = string + dice[i];
    }

    System.out.print(string);   

}

This is another way you can do it. Basically just makes a for-loop that accesses every element in the integer array and adds it to the string.




回答6:


 public static void main(String[] args) {

    System.out.println("Integer Value :" +convertIntToString(new int[]{3,4,5}));

  }

  public static String convertIntToString(int intArray[]) {
    List<Integer> listInteger = new ArrayList<Integer>();

    for (int i = 0; i < intArray.length; i++) {
        listInteger.add(intArray[i]);
    }

    Object o = listInteger;

    return String.valueOf(o).replace("[", "").trim().replaceAll(", ","").trim().replaceAll("\\]","").trim();
  }



回答7:


public static void main(String[] args) {
    System.out.println("Integer Value :" +convertIntToString(new int[]{3,4,5}));
}

public static String convertIntToString(int intArray[]) {
    List<Integer> listInteger = new ArrayList<Integer>();

    for (int i = 0; i < intArray.length; i++) {
        listInteger.add(intArray[i]);
    }

    Object o = listInteger;

    return String.valueOf(o).replace("[", "").trim().replaceAll(", ","").trim().replaceAll("\\]","").trim();
}


来源:https://stackoverflow.com/questions/3728563/best-way-to-convert-an-array-of-integers-to-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!