views:

147

answers:

6

Hi, I have a simple, general question regarding a real small issue that bothers me: I'm printing a list of elements on the fly, so I don't have prior knowledge about the number of printed elements. I want a simple format where the elements are separated by a comma (elem1, elem2...) or something similar. Now, if I use a simple loop like:

while(elements to check) {
  if (elem should be printed) {
     print elem . ","
  }
}

I get a comma after the last element... I know this sounds quite stupid, but is there a way to handle this?

A: 
scunliffe
then I have to first create an array, instead of printing-and-forgetting...
David B
sorry, I must be missing something... what data do you have to start with? e.g. several strings, a string array?, an ArrayList of Strings? or a Map or similar Object with keys/values?
scunliffe
It does not really maater, the point is I don't print the entire array/list; I check every element vs. some condition then decide whether I print it or not. So at the time of printing an element, I cannot tell if it's the last one to be printed.
David B
+2  A: 

Java does not have a build-in join, but if you don't want to reinvent the wheel, you can use Guava's Joiner. It can skipNulls, or useForNull(something).

An object which joins pieces of text (specified as an array, Iterable, varargs or even a Map) with a separator. It either appends the results to an Appendable or returns them as a String. Example:

Joiner joiner = Joiner.on("; ").skipNulls();
return joiner.join("Harry", null, "Ron", "Hermione");

This returns the string "Harry; Ron; Hermione". Note that all input elements are converted to strings using Object.toString() before being appended.

polygenelubricants
A: 

I guess the simplest way is to create a new array containing only the elements from the original array that you need to print (i.e. a filter operation). Then print the newly created array, preferably using your language's built-in array/vector print/join function.

(In Perl)

@orig=("a","bc","d","ef","g");
@new_list=();
for $x(@orig){
    push(@new_list,$x) if (length($x)==1);
}
print join(',',@new_list)."\n";

(In Java)

List<String> orig=Arrays.asList(new String[]{"a","bc","d","ef","g"});
List<String> new_list=new ArrayList<String>();
for(String x: orig){
    if (x.length()==1)
        new_list.add(x);
}
System.out.println(new_list);
MAK
Perl example is needlessly complicated, and not strict-safe.Much better and easier: use strict; use warnings; use 5.010; my @orig=("a","bc","d","ef","g"); say join(', ', grep { length > 1 } @orig);- Michael
mscha
A: 

Why not add a comma BEFORE each element (but the first one)? Pseudo-code:

is_first = true
loop element over element_array
BEGIN LOOP
   if (! is_first)
       print ","
   end if
   print element
   is_first = false
END
print NEWLINE
DVK
Don't forget to set the "is_first" variable to false. Otherwise, you'll never print that comma :)
Ovid
+3  A: 

the way of having all your data in an array and then

 print join(',', @yourarray)

is a good one.

You can also, after looping for your concatenation

declare eltToPrint
 while (LOOP on elt) {
       eltToPrint .= elt.','
}

remove the last comma with a regex :

eltToPrint =~s/,$//;

ps : works also if you put the comma at the beginning

eltToPrint =~s/^,//;
benzebuth
+4  A: 

Let's assume that "should be printed" means "at least one non-whitespace character. In Perl, the idiomatic way to write this would be (you'll need to adjust the grep to taste):

print join "," => grep { /\S/ } @elements;

The "grep" is like "filter" in other languages and the /S/ is a regex matching one non-whitespace character. Only elements matching the expression are returned. The "join" should be self-explanatory.

perldoc -f join
perldoc -f grep
Ovid
Go Perl! :)))))
DVK
isn't it unecessary to do the grep thing, as -- print join ',', @elements --just do the whole thing perfectly ?i just ask, to improve my own knowledge
benzebuth
benzebuth: the grep is only there to filter out undesired elements. However, you're correct that it could be dropped in the case the original poster mentioned. I typed too fast. Thanks :)
Ovid