How to Convert an Int Array to String with Tostring Method in Java

How to convert an int array to String with toString method in Java

What you want is the Arrays.toString(int[]) method:

import java.util.Arrays;

int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;

..

System.out.println(Arrays.toString(array));

There is a static Arrays.toString helper method for every different primitive java type; the one for int[] says this:

public static String toString(int[] a)

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(int). Returns "null" if a is null.

Converting an integer array to a String

int[] a = {1,2,3,4,5,6};

String str = "";

for(int i=0;i<a.length;i++)
{
str = str + Integer.toString(a[i]);
}
System.out.println(str);

Converting int array to String and returning (getArrayString)

Joining int[] to a String

Edit: I just spotted you have an int[] not a String[]. I would probably use the Streams approach:

String result = Arrays.stream(array)
.mapToObj(String::valueOf)
.collect(Collectors.joining(separator));

If you really want to use a for-loop, you should use a StringJoiner:

public static getArrayString(int[] array, char separator) {
if(array == null || array.length == 0) return "";

String separatorString = String.valueOf(separator);
StringJoiner sj = new StringJoiner(separatorString);

for(int element : array) {
sj.add(String.valueOf(element));
}

return sj.toString();
}

Joining String[] to a String

The phrasing of your question makes me think you're studying this for a class, but if you're not, just use the in-built join
function:

// join takes Iterable<? extends CharSequence> or vararg
String.join(separator, myArray)
String.join(separator, myList)
String.join(separator, charSeq1, charSeq2, ..., charSeqN)

If you need prefix/suffix, you can use a StringJoiner:

StringJoiner sj = new StringJoiner(separator, prefix, suffix);
String result = sj.add(s1).add(s2).add(s3).toString();

...which is also the basis of the Stream Collectors.joining:

String result = Arrays.stream(array)
.collect(Collectors.joining(separator));

String result = Arrays.stream(array)
.collect(Collectors.joining(separator, prefix, suffix));

Convert int[] to comma-separated string

Here's a stream version which is functionally equivalent to khelwood's, yet uses different methods.

They both create an IntStream, map each int to a String and join those with commas.

They should be pretty identical in performance too, although technically I'm calling Integer.toString(int) directly whereas he's calling String.valueOf(int) which delegates to it. On the other hand I'm calling IntStream.of() which delegates to Arrays.stream(int[]), so it's a tie.

String result = IntStream.of(intArray)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));

Convert int array to string without commas in java

int[] arr = new int[]{2, 3, 4, 1, 5};
String res = Arrays.toString(arr).replaceAll("[\\[\\],]", "");
System.out.println(res);

Convert any array of any type into string

Write a utility method like below:

public static String convertToString(Object input){
if (input instanceof Object[]) {
// deepToString used to handle nested arrays.
return Arrays.deepToString((Object[]) input);
} else {
return input.toString();
}
}

Please note that the first if condition would be evaluated to false if the input is a primitive array like int[], boolean[], etc. But it would work for Integer[] etc.
If you want the method to work for primitive arrays, then you need to add conditions for each type separately like:

else if (input instanceof int[]){
// primitive arrays cannot be nested.
// hence Arrays.deepToString is not required.
return Arrays.toString((Object[]) input);
}

Print an array in String without using Array.toString in Java

Problems

  • toString[i] is not a method call (toString() is), brackets [] are for array access
  • you misunderstand between arrays array and a
  • you method toString must return a String but you return nothing, and print all inside the method itself


Solution

  • the initial array must be defined in the main, and passed to the method
  • the method toString must build a String and return it
public static String toString(int[] a) {
StringBuilder sb = new StringBuilder("[" + a[0]);
for (int i = 1; i < a.length; i++) {
sb.append(", ").append(a[i]);
}
return sb.append("]").toString();
}

public static void main(String[] args) {
int[] array = {1, 2, 3, 4};
System.out.println(toString(array));
}


Improvement: handle empty array

It may be better to put all array access into the loop, because in case the array is empty, the previous code will fail at a[0]

public static String toString(int[] a) {
String join = "";
StringBuilder sb = new StringBuilder("[");
for (int val : a) {
sb.append(join).append(val);
join = ", ";
}
return sb.append("]").toString();
}

Example

System.out.println(toString(new int[]{1, 2, 3, 4})); // [1, 2, 3, 4]
System.out.println(toString(new int[]{})); // []

I want to print an array with a toString() method in java, but without brackets and commas (so, not with Arrays.toString())

Change array.toString() to toString(array). Also your method needs to be static because main method is static. And if you want to use it in print statement, then it should return something. That's why I have changed the return type of your method to String:

public static String toString(int[] num) { 
String s = "";
for (int index = 0; index < num.length; index++) {
s += num[index];
}
return s;
}

public static void main(String[] args) {
//test negative number, output should be -10000000
int largeNum1[] = {-2, 0, 0, 0, 0, 0, 0, 0};
int largeNum2[] = {1, 0, 0, 0, 0, 0, 0, 0};
int numSize1 = (largeNum1.length + largeNum2.length) + 1;
int[] sum1 = new int[numSize1];
int[] answer1 = sumNumbers(largeNum1, largeNum2, sum1);
System.out.println((toString(largeNum1)) + " + " + (toString(largeNum2)) + " = " + (toString(answer1)));
}


Related Topics



Leave a reply



Submit