In Java, I want to print the contents of a stack. The toString() method outputs them in square brackets, separated by commas: [foo, bar, baz] .
The question is, how do I get rid of them and print only the variables?
My code is:
Stack myStack = new Stack (); for(int j=0;j<arrayForVar.length;j++) { if(arrayForVar[j][1]!=null) { System.out.printf("%s \n",arrayForVar[j][1]+"\n"); myStack.push(arrayForVar[j][1]); } System.out.printf("%s \n",myStack.toString());
This answer worked for me:
Use the toString method on the stack and use the replaceAll method to replace all instances of square brackets with blankstring. Like this:
System.out.print( myStack.toString().replaceAll("\\[", "").replaceAll("]", ""));
source share