java - Name Reversing in strings -
write method lastnamefirst takes string containing name such "harry smith" or "mary jane lee", , returns string last name first, such "smith, harry" or "lee, mary jane".
im supposed check against http://wiley.code-check.org/codecheck/files?repo=bjlo2&problem=05_02
i post
string firstname = name.substring(0, name.indexof(" ")); string lastname = name.substring(name.indexof(" ")); string cname = lastname + ", " + firstname; if ( lastname == " " ) { cname = firstname; } return cname;
i 0/4 everytime please im lost.
it might simpler create array using split
function of string
class, join them:
string cname = string.join(", ", collections.reverse(arrays.aslist(name.split(" "))));
string.join
in java 8 believe, if you're not using 8 can use following:
string[] names = name.split(" "); string cname = names[1] + ", " + names[0];
you should using equals
method comparing string , other objects:
string[] names = name.split(" "); string cname = names[1].equals(" ") ? names[0] : names[1] + ", " + names[0];
Comments
Post a Comment