need help with logic for simple text-manipulation function

R

Rex

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
 
A

Andrew Thompson

Rex said:
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.
 
H

hiwa

Rex said:
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
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 + p);
}
return retval;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top