This question already has answers here:
Print out elements from an Array with a Comma between the elements
(14 answers)
Closed 8 years ago.
Trying to delete the last comma and instead add an end bracket. How to go about this?
My code:
#Override
public String toString(){
String str="[";
for(double d:data) str+=d+", ";
return str;
}
Example data:
stat1 data = [
stat1 data = [50.0, 60.0,
stat1 data = [70.0, 80.0,
stat1 data = [90.0, 100.0,
stat1 data = [100.0, 110.0,
stat1 data = [
Sometimes it's hard to tell, ahead of time, when an element you're looking at in an iterator is the last one. In cases like this, it often works best to append the comma before each element instead of after, except for the first element. Thus:
String str = "[";
boolean first = true;
for (double d : data) {
if (!first) {
str += ", ";
}
str += d;
first = false;
}
str += "]";
Another possibility is to use the logic you have now but use substring or replace or some other method to remove the extra two characters, like
str = str.replaceFirst(", $", "]");
which uses a regular expression to replace ", " that appears at the end of the string with a right bracket.
It's better to just print the data in the toString method and add the typographical elements like '[' or comma separately accompanied with an if statement.
However if you insist to stick just to the toString method, add a boolean field to the class and set it to true if something is the last object and inside the toString method, check that field and do the right decision.
Related
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
}
I have a method in my switch statement explaining to print my arraylist
(i.e - System.out.println(drinkList);)
ArrayList<String> drinkList = new ArrayList<String>();
System.out.print("Please enter a drink information to add:\n");
inputInfo = scan.nextLine().trim();
drinkLink = DrinkParser.parseStringToDrink(inputInfo);
drinkList.add(drinkLink.toString()); //Take in user data to parse into parts
Then I called it using the code
System.out.println(drinkList);
My problem is the output prints the following as such:
[
Data Entry 1
,
Data Entry 2
]
I want to remove the brackets and the comma.
Don't call the toString() method on the ArrayList but loop through it and build a string yourself. Do something like:
StringBuilder builder = new StringBuilder();
for (String value : drinkList) {
builder.append(value) + ",";
}
String text = builder.toString();
System.out.println(text);
That'll make sure that the resulting string has the format that you want - in this case comma-separated entries.
Use the following code to remove the brackets and the commas:
String s = "[\nData Entry 1\n,\n Data Entry 2\n]";
String result = s.replaceAll("[^\\dA-Za-z\n]", "");
System.out.println(result);
The result is:
Data Entry 1
Data Entry 2
Or, you can override toString() method for your class.
This question already has answers here:
What's the best way to build a string of delimited items in Java?
(37 answers)
Closed 8 years ago.
Replacing square brackets is not a problem, but the problem is with replacing commas,
replace(",", "") , because it does it with all commas in my table and i need to delete only those which appears because of Arrays.toString()
System.out.println( Arrays.toString( product ).replace("[", "").replace("]", "").replace(",", ""));
If there is no way of do that, maybe there are other ways to print my array, like string builder...etc? but i am not sure how to use it
Rather than using Arrays.toString, since you don't want the output it creates, use your own loop:
StringBuilder sb = new StringBuilder(400);
for (int i = 0; i < product.length; ++i) {
sb.append(product[i].toString());
}
String result = sb.toString();
Note I'm using toString on your product entries; there may be a more appropriate choice depending on what those are.
If you want a delimiter (other than ,, obviously), just append it to the StringBuilder as you go:
StringBuilder sb = new StringBuilder(400);
for (int i = 0; i < product.length; ++i) {
if (i > 0) {
sb.append(yourDelimiter);
}
sb.append(product[i].toString());
}
String result = sb.toString();
We dont know what your objects look like in your array, but you shouldnt use Arrays.toString if you dont like the output since its only a helper method to save you some time. Just iterate over your objects with a loop and print them.
There's a great library of apache where you can achieve your goal in one line of code:
org.apache.commons.lang.StringUtils
String delimiter = " ";
StringUtils.join(array, delimiter);
I have the String like:
String value = "13,14,15,16,17"
But i Dont know how many numbers are there with comma separation.
I want to compare with the variable say:
String varValue = "16"
It may be in any postion..
I want to compare these two string variables....
Please can anyone help?
You can do this sort of thing:
String values = '13,14,15,16,17'
String required = '16'
values.tokenize( ',' ).with { toks ->
println "There are ${toks.size()} elements in the list"
println "The list contains $required is ${toks.contains( required )}"
println "It is at position ${toks.indexOf( required )}"
}
Which prints
There are 5 elements in the list
The list contains 16 is true
It is at position 3
Use the split method to put the numbers in an array and then compare.
Here: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
Do not quite understand your question.
Dont know how many numbers are there with comma separation
use String method split()
I want to compare with the variable say: String varValue = "16"
use String method contains()
You can use the split method to receive an Array. Turning the Array into a List will allow you to use some helper functions such as contains and indexOf, which can be used to return whether the token exists or the position of the token.
String value = "13,14,15,16,17";
//Checks existence
boolean contains = Arrays.asList(value.split(",")).contains("16");
//Returns position
int pos = Arrays.asList(value.split(",")).indexOf("16") + value.split(",").length + 1;
These examples all use Java.
If you are using Java , then following can be done to achieve this :
1. Split the input string into an array.
2. convert that array into a list .
Now
a) To find total elements separated by comma , Use :
size().
b) To find if the list contains required element or not , Use :
contains().
c) To find position of element in list , Use :
indexof()
So the code will look like :
import java.util.Arrays;
import java.util.List;
public class Test{
public static void main(String[] args) {
String inputString = "13,14,15,16,17";
String element = "16";
// Convert the string into array.
String values[] = inputString.split(",");
// Create a list using array elements.
List<String> valList = Arrays.asList(values);
System.out.println("Size :" + valList.size());
System.out.println("List contains 5 " + valList.contains(element));
System.out.println("Position of element" + valList.indexOf(element));
}
}
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);