[resolved] Splitting A String At The Last Space

Five Stars

[resolved] Splitting A String At The Last Space

I have used Talend variables and expressions in tMap to split a string at the space, as in a normal name field.  That works for most cases, where there is a first and last name.  For example, "Mickey Mouse" can be split into "Mickey" as the First Name, and "Mouse" as the Last Name. 
I would like to know if there is a way to split a string at the last space.  I'd like to be able to take a string such as "John and Mary Jones", and split off the "Jones" part to become the Last Name, and "John and Mary" to be the First Name.
Thanks in advance!
HL

Accepted Solutions
Five Stars

Re: [resolved] Splitting A String At The Last Space

Hi Shong,
Thanks very much for the code - that did it!  I modified the expression to account for one-word names, and also to TRIM the string.
HL

All Replies
Community Manager

Re: [resolved] Splitting A String At The Last Space

Hi 
Search the last index of space, and truncate the string, for example;
tFileInputDelimited--main--tMap--tlogRow
For first name:
row1.name.substring(0,row1.name.lastIndexOf(" "))
For last name:
row1.name.substring(row1.name.lastIndexOf(" ")+1)
Best regards
Shong
----------------------------------------------------------
Talend | Data Agility for Modern Business
Five Stars

Re: [resolved] Splitting A String At The Last Space

Hi Shong,
Thanks very much for the code - that did it!  I modified the expression to account for one-word names, and also to TRIM the string.
HL
One Star

Re: [resolved] Splitting A String At The Last Space

Hi Hleyes.
Could you share your solution for future generations?
Thanks.
BR, one-in-need
Community Manager

Re: [resolved] Splitting A String At The Last Space

Hi JamesBrown 
I suggest you to open a new topic for your question and describe it with more information, so you can gain more help from community users. 
Best regards
Shong
----------------------------------------------------------
Talend | Data Agility for Modern Business