fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. System.out.println(combine("ABCD", "abcdef"));
  13. System.out.println(combine("ABCDEF", "abcd"));
  14. System.out.println(combine("ABCDEF", "abcdef"));
  15. System.out.println(combine("ABCD", null));
  16. System.out.println(combine(null, "abcd"));
  17. System.out.println(combine(null, null));
  18. }
  19.  
  20. public static String combine(String str1,String str2) {
  21. StringBuilder result = new StringBuilder();
  22. int str1size = str1 == null ? 0 : str1.length();
  23. int str2size = str2 == null ? 0 : str2.length();
  24. int lowerSize = Math.min(str1size, str2size);
  25. int greaterSize = Math.max(str1size, str2size);
  26. int i; // define the counter variable outside of a for, because we will reuse it in the following for loops
  27. for (i=0; i < lowerSize; i++) { // browse the common part of the strings
  28. result.append(str1.charAt(i)).append(str2.charAt(i));
  29. }
  30. for (int upTo = Math.min(greaterSize, str1size); i < upTo ; i++) { // browse the remaining part of str1, if applicable
  31. result.append(str1.charAt(i));
  32. }
  33. for (int upTo = Math.min(greaterSize, str2size); i < upTo; i++) { // browse the remaining part of str2, if applicable
  34. result.append(str2.charAt(i));
  35. }
  36. return result.toString();
  37. }
  38. }
Success #stdin #stdout 0.09s 320512KB
stdin
Standard input is empty
stdout
AaBbCcDdef
AaBbCcDdEF
AaBbCcDdEeFf
ABCD
abcd