SQDK
SQDK

Reputation: 4227

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

Upvotes: 62

Views: 226953

Answers (13)

Andy amurs
Andy amurs

Reputation: 1

String withoutBrackets = List.of("a", "b")
                                 .toString()
                                 .replaceAll("[]\\[,]", "");
System.out.println(withoutBrackets);

//output: a, b

Upvotes: -1

touqeer
touqeer

Reputation: 407

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

Upvotes: 0

David
David

Reputation: 1770

the most simple solution for removing the brackets is,

  1. convert the arraylist into string with .toString() method.

  2. use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).

  3. the result string is your string with removed brackets.

Upvotes: 4

icastell
icastell

Reputation: 3605

For Android, you can use the join method from android.text.TextUtils class like:

TextUtils.join("",array);

Upvotes: 27

douglas
douglas

Reputation: 116

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

Upvotes: 1

im_grownish
im_grownish

Reputation: 9

String[] students = {"John", "Kelly", "Leah"};

System.out.println(Arrays.toString(students).replace("[", "").replace("]", " "));

//output: John, Kelly, Leah

Upvotes: 0

Marko Panushkovski
Marko Panushkovski

Reputation: 63

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.

Upvotes: 3

ernest_k
ernest_k

Reputation: 45309

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.

Upvotes: 16

Namo
Namo

Reputation: 669

If you use Java8 or above, you can use with stream() with native.

publicArray.stream()
        .map(Object::toString)
        .collect(Collectors.joining(" "));

References

Upvotes: 13

user489041
user489041

Reputation: 28294

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

Upvotes: 115

AlexR
AlexR

Reputation: 115328

first

StringUtils.join(array, "");

second

Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")

EDIT

probably the best one: Arrays.toString(arr)

Upvotes: 20

jazkat
jazkat

Reputation: 5788

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500225

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.)

Upvotes: 65

Related Questions