开发者

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 format开发者_Go百科ted 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,

  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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜