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"
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"
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.
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.
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(""));
StringBuffer str =new StringBuffer();
for(int i:x){
str.append(i);
}
You need to read all once at least.
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.
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();
}
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();
}