Reputation: 149
I have searched this site for a solution and while there are many, many solutions for string handling, I didn't see anything like this.
If I have a middle name/names in the string, I want to remove it/them (e.g. 'Tommy Lee Jones' or 'Tommy Lee Brian Jones' becomes 'Tommy Jones', ).
Since the names could be of varying length, I assume that you would need to detect the white space either side of the middle names and then somehow create the new string with what was before and after the whitespace adding a space in between. If it's only possible with 3 names, I would work with that.
Any solutions or even pointers in the right direction appreciated thanks!
Upvotes: 0
Views: 93
Reputation: 12336
start with the string ..
... separate by spaces. this gives an array
get the length of the array. example, say it is "3"
the first index is "zero". the last index is length-1. in our example, the length is 3, so the last index is 2.
the firstname is the array[0]
the last name is the array[last index]
you're done!
this always works, with any number of names, even if only one name such as "Madonna".
be careful to check first that the input string is not blank.
Upvotes: 2