java - Trying to understand following code for reversing a sentence -
please consider code below:
public class sentencereversal { /** * @param args */ public static void main(string[] args) { string[] parts = "this interview question".split("\\b"); stringbuilder sb = new stringbuilder(); (int = parts.length; --> 0 ;) { sb.append(parts[i]); } system.out.println("[" + sb.tostring() + "]"); } }
what "\b" doing in split function? removing producing following result(that means using split("")):
[noitseuq weivretni na si siht]
also, `-->' operator doing in loop? didn't quite understand. please me in understanding questions.
thanks
string.split()
splits string based on regular expression.
\b
regex expression , denotes word boundary i.e. start of line, end of line, space, punctuation marks etc. it's passed \\b
because java needs \
escaped \
.
when split() ""
you're splitting on nothing , hence input string gets broken individual letters in array gets iterated in reverse , hence string of letters (instead of words) reversed.
just elaborate on @luiggimendoza's observations
i --> 0 // gets interpreted i-- > 0 // i.e. uses post-fix decrement operator
which means value of i
gets comapred 0
first , i = - 1
happens.
also, notice use of stringbuilder
instead of stringbuffer
(thread-safe slow) or plain string
concatenation (would have created many unnecessary strings in java string pool).
Comments
Post a Comment