string - Change order of words Java -
i cannot figure out how change order of given name.
for example: van-dame claud result: claud dame-van
i created method, seems not correct, suggestion or maybe better method?
public string nameinvers(){ string name, name = null, name = null, namefinal; int s1 = getname().indexof(' '); int s2 = getname().indexof('-'); if(s1 != 0){ name1 = getname().substring(0, s1); if(s2 != 0) { name2 = getname().substring(s1, s2); name3 = getname().substring(s2); } namefinal = name3 + name2 + name1; } else namefinal = getname(); return namefinal; }
edit: in main method have number of names. thing says: throw new stringindexoutofboundsexception(sublen) , won't show up.
here go:
public static string reversename (string name) { name = name.trim(); stringbuilder reversednamebuilder = new stringbuilder(); stringbuilder subnamebuilder = new stringbuilder(); (int = 0; < name.length(); i++) { char currentchar = name.charat(i); if (currentchar != ' ' && currentchar != '-') { subnamebuilder.append(currentchar); } else { reversednamebuilder.insert(0, currentchar + subnamebuilder.tostring()); subnamebuilder.setlength(0); } } return reversednamebuilder.insert(0, subnamebuilder.tostring()).tostring(); }
test:
public static void main(string[] args) { printtest("van-dame claud"); printtest("victor hugo"); printtest("anna"); printtest(""); } private static void printtest(string s) { system.out.printf("reverse name %s: %s\n", s, reversename(s)); }
output:
reverse name van-dame claud: claud dame-van reverse name victor hugo: hugo victor reverse name anna: anna reverse name :
Comments
Post a Comment