Convert int[] to comma-separated string - java

How can I convert int[] to comma-separated String in Java?
int[] intArray = {234, 808, 342};
Result I want:
"234, 808, 342"
Here are very similar reference question but none of those solution provide a result, exact I need.
How to convert an int array to String with toString method in Java
How do I print my Java object without getting "SomeType#2f92e0f4"?
How to convert a List<String> into a comma separated string without iterating List explicitly
What I've tried so far,
String commaSeparatedUserIds = Arrays.toString(intArray); // result: "[234, 808, 342]"
String commaSeparatedUserIds = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", ""); // result: "234808342"
String commaSeparatedUserIds = intArray.toString(); // garbage result

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(", "));

This should do
String arrAsStr = Arrays.toString(intArray).replaceAll("\\[|\\]", "");
After Arrays toString, replacing the [] gives you the desired output.

int[] intArray = {234, 808, 342, 564};
String s = Arrays.toString(intArray);
s = s.substring(1,s.length()-1);
This should work. basic idea is to get sub string from Arrays.toString() excluding first and last character
If want quotation in result, replace last line with:
s = "\"" + s.substring(1,s.length()-1) + "\"";

You want to convert the ints to strings, and join them with commas. You can do this with streams.
int[] intArray = {234, 808, 342};
String s = Arrays.stream(intArray)
.mapToObj(String::valueOf) // convert each int to a string
.collect(Collectors.joining(", ")); // join them with ", "
Result:
"234, 808, 342"

This is the pattern I always use for separator-joining. It's a pain to write this boilerplate every time, but it's much more efficient (in terms of both memory and processing time) than the newfangled Stream solutions that others have posted.
public static String toString(int[] arr) {
StringBuilder buf = new StringBuilder();
for (int i = 0, n = arr.length; i < n; i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(arr[i]);
}
return buf.toString();
}

Related

Is there a way to concatenate Java strings in less than O(n) time?

My homework question involves joining strings in a particular sequence. We are first given the strings, followed by a set of instructions that tell us how to concatenate them; finally we print the output string.
I have used the Kattis FastIO class to handle buffered input and output. Below is my algorithm, which iterates through the instructions to concatenate the strings. I have tried making the array of normal strings, StringBuffers and StringBuilders.
The program seems to work as intended, but it gives a time limit error on my submission platform due to inefficiency. It seems like appending the way I did is O(n); is there any faster way?
public class JoinStrings {
public static void main(String[] args) {
Kattio io = new Kattio(System.in, System.out);
ArrayList<StringBuilder> stringList = new ArrayList<StringBuilder>();
int numStrings = io.getInt();
StringBuilder[] stringArray = new StringBuilder[numStrings];
for (int i = 0; i < numStrings; i++) {
String str = io.getWord();
stringArray[i] = new StringBuilder(str);
}
StringBuilder toPrint = stringArray[0];
while (io.hasMoreTokens()) {
int a = io.getInt();
int b = io.getInt();
stringArray[a-1].append(stringArray[b-1]); // this is the line that is done N times
toPrint = stringArray[a-1];
}
io.println(toPrint.toString());
io.flush();
}
}
The StringBuilder.append() copy char from new string to existing string. It's fast but not free.
Instead of keeping appending the String to the StringBuilder array, keep track of the String indexes need to appended. Then finally append the Strings stored in the print out indexes list.

simple mathematical expression parsing

I try to write equals override function. I think I have written right but the problem is that parsing the expression. I have an array type of ArrayList<String> it takes inputs from keyboard than evaluate the result. I could compare with another ArrayList<String> variable but how can I compare the ArrayList<String> to String. For example,
String expr = "(5 + 3) * 12 / 3";
ArrayList<String> userInput = new ArrayList<>();
userInput.add("(");
userInput.add("5");
userInput.add(" ");
userInput.add("+");
userInput.add(" ");
userInput.add("3");
.
.
userInput.add("3");
userInput.add(")");
then convert userInput to String then compare using equals
As you see it is too long when a test is wanted to apply.
I have used to split but It splits combined numbers as well. like 12 to 1 and 2
public fooConstructor(String str)
{
// ArrayList<String> holdAllInputs; it is private member in class
holdAllInputs = new ArrayList<>();
String arr[] = str.split("");
for (String s : arr) {
holdAllInputs.add(s);
}
}
As you expect it doesn't give the right result. How can it be fixed? Or can someone help to writing regular expression to parse it properly as wanted?
As output I get:
(,5, ,+, ,3,), ,*, ,1,2, ,/, ,3
instead of
(,5, ,+, ,3,), ,*, ,12, ,/, ,3
The Regular Expression which helps you here is
"(?<=[-+*/()])|(?=[-+*/()])"
and of course, you need to avoid unwanted spaces.
Here we go,
String expr = "(5 + 3) * 12 / 3";
.
. // Your inputs
.
String arr[] = expr.replaceAll("\\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])");
for (String s : arr)
{
System.out.println("Element : " + s);
}
Please see my expiriment : http://rextester.com/YOEQ4863
Hope it helps.
Instead of splitting the input into tokens for which you don't have a regex, it would be good to move ahead with joining the strings in the List like:
StringBuilder sb = new StringBuilder();
for (String s : userInput)
{
sb.append(s);
}
then use sb.toString() later for comparison. I would not advice String concatenation using + operator details here.
Another approach to this would be to use one of the the StringUtils.join methods in Apache Commons Lang.
import org.apache.commons.lang3.StringUtils;
String result = StringUtils.join(list, "");
If you are fortunate enough to be using Java 8, then it's even easier...just use String.join
String result = String.join("", list);
More details on this approach available here
this makes all the inputs into one string which can then be can be compared against the expression to see if it is equal
String x = "";
for(int i = 0; i < holdAllInputs.length; i++){
x = x + holdAllInputs.get(i);
}
if(expr == x){
//do something equal
}else{
//do something if not equal
}

How to get rid of the braces and commas returned by Arrays.toString()?

Consider this code-
import java.util.Arrays;
class Test {
public static void main(String args[]) {
int[] arr=new int[5];
for (int i=0; i<5; i++) {arr[i]=i;}
String sarr=Arrays.toString(arr);
System.out.println(sarr);
}
}
The output is-
[0, 1, 2, 3, 4]
I want to know weather there is a way to get rid of the braces and the commans introduced by toString()?? I want my String to be like this-
"01234"
Just build the string yourself, with a StringBuilder:
StringBuilder builder = new StringBuilder();
for (int value : arr) {
builder.append(value);
}
String text = builder.toString();
Basically if you don't want the formatting that Arrays.toString provides you, I'd avoid using it in the first place.
The best way to get rid of the characters that you do not want is to not put them in in the first place:
StringBuilder sb = new StringBuilder();
for (int n : arr) {
sb.append(n);
}
String sarr = sb.toString();
However, if you must remove the punctuation after the fact, you could use replaceAll:
sarr = sarr.replaceAll("[^0-9]", "");
You could use fast enumeration and StringBuilder - maybe into a static method taking int[] as argument.
For instance:
int[] arr = new int[] {0,1,2,3,4};
StringBuilder sb = new StringBuilder(arr.length);
for (int i: arr) {
sb.append(i);
}
System.out.println(sb.toString());
Output:
01234
You could remove all non digit characters:
String sarr = Arrays.toString(arr).toString().replaceAll("\\D+", "");
I would recommend not relying on the toString() representation from Arrays, since it is mostly meant for easier debugging, not for any productive use. If you want the information in a certain structured way, format it that way yourself (e.g. by looping over the array and appending to a StringBuilder).

Print array without brackets and commas

I'm porting a Hangman game to Android and have met a few problems. The original Java program used the console, so now I have to somehow beautify the output so that it fits my Android layout.
How do I print an array without the brackets and commas? The array contains slashes and gets replaced one-by-one when the correct letter is guessed.
I am using the usual .toString() function of the ArrayList class and my output is formatted like: [ a, n, d, r, o, i, d ]. I want it to simply print out the array as a single String.
I fill the array using this bit of code:
List<String> publicArray = new ArrayList<>();
for (int i = 0; i < secretWordLength; i++) {
hiddenArray.add(secretWord.substring(i, i + 1));
publicArray.add("-");
}
And I print it like this:
TextView currentWordView = (TextView) findViewById(R.id.CurrentWord);
currentWordView.setText(publicArray.toString());
Replace the brackets and commas with empty space.
String formattedString = myArrayList.toString()
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.trim(); //remove trailing spaces from partially initialized arrays
Basically, don't use ArrayList.toString() - build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray when it's not actually an array, by the way.)
For Android, you can use the join method from android.text.TextUtils class like:
TextUtils.join("",array);
first
StringUtils.join(array, "");
second
Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")
EDIT
probably the best one: Arrays.toString(arr)
With Java 8 or newer, you can use String.join, which provides the same functionality:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter
String[] array = new String[] { "a", "n", "d", "r", "o", "i", "d" };
String joined = String.join("", array); //returns "android"
With an array of a different type, one should convert it to a String array or to a char sequence Iterable:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
//both of the following return "1234567"
String joinedNumbers = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).toArray(n -> new String[n]));
String joinedNumbers2 = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).collect(Collectors.toList()));
The first argument to String.join is the delimiter, and can be changed accordingly.
If you use Java8 or above, you can use with stream() with native.
publicArray.stream()
.map(Object::toString)
.collect(Collectors.joining(" "));
References
Use Java 8 Language Features
JavaDoc StringJoiner
Joining Objects into a String with Java 8 Stream API
the most simple solution for removing the brackets is,
convert the arraylist into string with .toString() method.
use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).
the result string is your string with removed brackets.
I have used
Arrays.toString(array_name).replace("[","").replace("]","").replace(", ","");
as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.
I used join() function like:
i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");
Which Prints:
HiHelloCheersGreetings
See more: Javascript Join - Use Join to Make an Array into a String in Javascript
String[] students = {"John", "Kelly", "Leah"};
System.out.println(Arrays.toString(students).replace("[", "").replace("]", " "));
//output: John, Kelly, Leah
You can use the reduce method provided for streams for Java 8 and above.Note you would have to map to string first to allow for concatenation inside of reduce operator.
publicArray.stream().map(String::valueOf).reduce((a, b) -> a + " " + b).get();
I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.
Please refer to my Code & Output below:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
System.out.println("Enter Value " + i + " to add: ");
mylist.add(scan.nextLine());
}
System.out.println("=======================");
for(int j = 0; j < 5; j++) {
System.out.print(mylist.get(j));
}
}
}
OUTPUT
Enter Value 0 to add:
1
Enter Value 1 to add:
2
Enter Value 2 to add:
3
Enter Value 3 to add:
4
Enter Value 4 to add:
5
=======================
12345
Just initialize a String object with your array
String s=new String(array);

Getting all the values of an array of Strings in one String

if I have,
String[] s = new String[3];
s[0] = "Ap";
s[1] = "p";
s[2] = "le";
String result = ?
If I want to get Apple out of s without looping, how do I do that?
Any short cut?
If the not looping is more important to you than preventing to import another library or if you are using apache commons lang already, anyway, you can use the StringUtils.join method
import org.apache.commons.lang.StringUtils;
String joined = StringUtils.join(s, "");
Maybe the Apache Commons have other methods that might be interesting for your project, as well. I found them to be a very useful resource for missing features in the native Java libraries.
Without looping, you can:
public String joinpart(String[] a, int i, String prefix) {
if (i < a.length) {
return joinpart(a, i + 1, prefix + a[i]);
}
return prefix;
}
then:
String[] a = new String[]{"Ap", "p", "le"};
String apple = joinpart(a, 0, "");
This is called a recursive solution.
If you know the length of your array, you can easily do the following:
String result = s[0] + s[1] +s[2];
Another option is to do the following, (which is purely academic, I would not use it in a real-world scenario as it would remove [, ], and <space> from your strings):
String result = Arrays.toString(s).replaceAll("[\\]\\[, ]", "");
Yet another option, to go along with the first attempt, but using a C-like formatter:
System.out.println(String.format("%s%s%s", s));
using Dollar is simple as typing:
String[] array = new String[] { "Ap", "p", "le" };
String result = $(array).join(); // result now is "Apple"
String result = s[0] + s[1] + s[2];
If you have an unknown number of entries, I think you'll need a loop.
Java does not have a String.join() type method. You'll have to roll one yourself if you want to hide the loop.

Categories