Attach the lines with a separator and strip out the blanks.

I need code logic for the following:

These are three string variables,

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

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

  • Scenario No. 1 The actual output should be "A / B / C"
  • Scenario # 2 When s1 is empty, the output should be "B / C"
  • Scenario No. 3 When s2 is empty, the output should be "A / C"
  • Scenario # 4 When s3 is empty, the output should be "A / B" `

Is this possible using triple operation?

+6
source share
5 answers

You can do:

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

Take a look

+1
source

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

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

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

+10
source

java8-way with stream

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

This is not a true answer, because I will not use the ternary operator here.

If you need to combine lines that delete empty ones, you can write a general function (without error checking, without optimization, 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(); } 

This is a rather long version than the "built-in" version, but it works regardless of the number of lines you want to join (and you can change it to use a variable number of parameters). This will make the code in which you will use it much more clearly than any if tree.

Something like that:

 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
source
 String ans = (s1 == null ? s2 + "/" + s3 : (s2 == null ? s1 + "/" + s3 : (s3 == null ? s1 + "/" + s2 : s1 + "/"+ s2 + "/" + s3 ))); 

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

0
source

Source: https://habr.com/ru/post/915645/


All Articles