8

I need the code logic for the following:

These are the three String variables,

String s1 = "A"; String s2 = "B"; String s3 = "C"; 

I need to have the following outputs based on the given scenarios:

  • Scenario #1 Actual output should be "A / B / C"
  • Scenario #2 When s1 is empty, output should be "B / C"
  • Scenario #3 When s2 is empty, output should be "A / C"
  • Scenario #4 When s3 is empty, output should be "A / B"`

Is this possible using ternary operation?

5
  • 2
    Of course yes but don't you think it's MUCH more easy to read using "plain" if statements? I mean: you know the ternary operator but to use it in cascade isn't clear for you then it'll be less clear for whom will read your code. Commented May 14, 2012 at 8:21
  • what about the other four scenarios? Are they possible, too? Commented May 14, 2012 at 8:21
  • Yes, it's possible. However, I wouldn't use the ternary operator for this. Commented May 14, 2012 at 8:23
  • I don't want to use nested if conditions. I'd like to have a two or three liner to solve this. Any ideas? That's why I asked whether this can be achieved using ternary operator. Commented May 14, 2012 at 8:27
  • if won't be nested, just in cascade (compare with code in answers, do you think ternary is more clear?). You may implement a join method like in StringUtils (or to use it). It'll be readable, reusable and...short. Commented May 14, 2012 at 8:34

5 Answers 5

11

You can do it with with the help of Guava class Joiner and Apache Commons Lang StringUtils.defaultIfBlank:

Joiner.on("/").skipNulls().join( defaultIfBlank(s1, null), defaultIfBlank(s2, null), defaultIfBlank(s3, null) ); 

You can extract the three lines of "defaultIfBlank" into a method with a loop if you need to process an arbitrary number of strings.

Sign up to request clarification or add additional context in comments.

2 Comments

On first read I completely oversaw the ".skipNulls()" which is gold here. Didn't even know its existance yet. Super easy with something "skippable" :)
Or use Guava's Strings.emptyToNull instead of defaultIfBlank if you only want to use the Guava library.
3

A java8-way with a stream

Arrays.stream(new String[]{null, "", "word1", "", "word2", null, "word3", "", null}) .filter(x -> x != null && x.length() > 0) .collect(Collectors.joining(" - ")); 

Comments

2

You can do:

result = ((s1==null)?"":(s1+"/"))+((s2==null)?"":(s2+"/"))+((s3==null)?"":s3); 

See it

2 Comments

with s1 = "A", s2 = "B" and s3 = null, you get A/B/ wich is incorrect.
It's wrong. Separators need to be conditioned on the preceding result, which either requires separate statements/ or the later ternary conditions to be checking all the previous terms.
2

This isn't a true answer because I won't use here the ternary operator.

If you need to concatenate strings removing the empty ones you can write a generic function (no error checking, no optimizations, take it as an example):

public static String join(String[] array, char separator) { StringBuffer result = new StringBuffer(); for (int i = 0; i < array.length; ++i) { if (array[i] != null && array[i].length() != 0) { if (result.length() > 0) result.append(separator); result.append(array[i]); } } return result.toString(); } 

It's pretty longer than the "inline" version but it works regardless the number of strings you want to join (and you can change it to use a variable number of parameters). It'll make the code where you'll use it much more clear than any sort of if tree.

Something like this:

public static String join(char separator, String... items, ) { StringBuffer result = new StringBuffer(); for (String item: items) { if (item != null && item.length() != 0) { if (result.length() > 0) result.append(separator); result.append(item); } } return result.toString(); } 

2 Comments

Thanks for the answer. But the unwanted '/' should also be removed for each scenario. For example, if s2 is empty, the output should be "A / C" and not "A / / C". same for the other scenario if s1 is empty, o/p should be "B / C" not "/ B / C". Still need too many lines of code huh? :)
@Marshal yes, updated the answer to handle that. Yes, many more lines of code but 99.9999% times the point isn't if code is long or not but if it's readable, reusable and not error prone. Anyway this wasn't intended to answer your question but to provide an example of join function for strings! :)
0
String ans = (s1 == null ? s2 + "/" + s3 : (s2 == null ? s1 + "/" + s3 : (s3 == null ? s1 + "/" + s2 : s1 + "/"+ s2 + "/" + s3 ))); 

won't suggest using it though!! too unreadable!!

2 Comments

I agree with you about readability. It'll get even more unreadable once you start checking for the empty string rather than null, and once you start concatenating actual input strings rather than hard-coding "A/B" etc.
I suspect this is homework, which I find seems to require that we produce unreadable code sometimes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.