Re: How to find first space in string name
in message <1159762318.128202.315340@e3g2000cwe.googlegroups.com>,
naeron@gmail.com ('naeron@gmail.com') wrote:
Hi,
I am new to java programming .I have this programme for which i am
entering the first name and last name via a string e.g Bob Thomas and
then sorting the names.Can some body tell me that after entering the
name how can i find the space in the string e.g how should i program
that after Bob if there is a space that means it was the first name.
To find the remainder of a string after the first space
String name = "Bob Thomas";
String surname = name;
int offset = name.indexOf( ' ');
if ( offset > -1)
{
surname = name.substring( space + 1);
}
To find the remainder after the /last/ space (which is I think what you
really want, substitute lastIndexOf for indexOf in the above. However, to
protect yourself from bad formatting which has spaces on either the
beginning or the end of the string, I'd use
public String surname( String name)
{
String result = name;
try
{
result = name.trim();
result = result.substring( result.lastIndexOf( ' ') + 1);
}
catch ( Exception any)
{
/* NullPointer (possible) or IndexOutOfBounds (shouldn't
happen); in any case, ignore */
}
return result;
}
Not testing for validity but just letting the exception handler catch
problems saves a few cycles on every 'good' call, at a considerable cost
on every 'bad' call; but if you're reasonably sure the input data is in
reasonable state it's probably a saving over all.
--
simon@jasmine.org.uk (Simon Brooke) http://www.jasmine.org.uk/~simon/
The Conservative Party now has the support of a smaller proportion of
the electorate in Scotland than Sinn Fein have in Northern Ireland.