Java How do I merge all char from an array of String into a new String? -


i'm making method

public static string merge(string... s) 

this input:

string = merge("am ","l","geds","oratkrr","","r trte","io","tgauu"); system.out.println(a); 

expected output:

algoritmer og datastrukturer 

i try run loop many times picks s[0].charat(index) , appends string output. problem run when try run loop s[1].charat(1) it's null, want not stringindexoutofboundsexception, , instead continue s[2] , appends s[2].char string.

how go that?

you need check length of each string before trying access i'th character :

stringbuilder sb = new stringbuilder(); int index = 0; boolean maxlengthreached = false; while (!maxlengthreached) {     maxlengthreached = true;     (string str : input) {         if (index < str.length) {             sb.append(str.charat(index));             maxlengthreached = false;         }     }     index++; }  return sb.tostring(); 

just clarify, i'm using boolean maxlengthreached determine when last character of longest string appended output. if in full iteration on strings in input array don't find string long enough have charat(index), know done.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -