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

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -