Hi I want to write a method which takes in a string of names
seperated by a whitespace and puts commas at each whitespace the last
name however, should have "and" before it.
Let me explain this with the help of an example:
The original string is: "Toby Grant Michelle Tom" the procedure should
return "Toby, Grant, Michelle and Tom"
Cheers!
Rex
Andrew Thompson - 21 Nov 2006 02:46 GMT
> Hi I want to write a method which takes in a string of names
> seperated by a whitespace and puts commas at each whitespace the last
> name however, should have "and" before it.
Excellent - let us know how that goes.
Andrew T.
hiwa - 21 Nov 2006 03:36 GMT
> Hi I want to write a method which takes in a string of names
> seperated by a whitespace and puts commas at each whitespace the last
[quoted text clipped - 7 lines]
> Cheers!
> Rex
public class Rex{
public static void main(String[] args){
String text ="Toby Grant Michelle Tom";
System.out.println(pconvert(text));
}
public static String pconvert(String nlist){
String retval = "";
nlist = nlist.trim();
String[] nams = nlist.split("\\s+");
for (int i = 0; i < nams.length; ++i){
String p = i == (nams.length - 2) ? " and " : ", ";
if (i == (nams.length - 1)){
p = "";
}
retval += (nams[i] + p);
}
return retval;
}
}