Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2006

Tip: Looking for answers? Try searching our database.

need help with logic for simple text-manipulation function

Thread view: 
Rex - 21 Nov 2006 01: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.

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;
 }
}


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.