String.split(String regex, int limit) question

Take the string:

2000 S 900 W

Is there a way in which I could use the split method on this string such that the contents of the String array are:
2000 S
900 W

As far as I know, the spilt method cannot return delimiters.  So, if this is true, can someone tell me how I can do this efficiently?  
rnicholusAsked:
Who is Participating?
 
InteractiveMindConnect With a Mentor Commented:

String str = "2000 S 900 W 50 E";    // For example; for this to work, it must take this format.

String [] tokens = str.split( " " );
String [] results = null;
if ( tokens.length % 2 == 0 )   // If an even number of tokens.
{
    results = new String [tokens.length/2];
    int count = 0;
    for ( int i = 0; i < tokens.length; i++ )
    {
        if ( i % 2 != 0 )
        {
            results[count] = tokens[i] + " " + tokens[i+1];
            ++count;
        }
    }
}

Then, you can do this:

if ( results != null )
{
    // A String array, called 'results' exists, containing exactly what you're after! :-)
}
0
 
InteractiveMindCommented:
No, not with the String#split() method.

If there's always 4 tokens, then you can do something like this:

String str = "2000 S 900 W";
StringTokenizer st1 = new StringTokenizer( str, " " );

String token1 = st1.nextToken();
token1 += st1.nextToken();
String token2 = st1.nextToken();
token2 += st1.nextToken();
0
 
rnicholusAuthor Commented:
Actually, there aren't always 4 tokens.  Sometime there may be 6, sometime 2.  Oh well.
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
InteractiveMindCommented:
Before you accept anything, let me see if I can produce a solution for that instead...
0
 
rnicholusAuthor Commented:
After talking with my data engineer, I just realized that these are street suffixes, and I can't use them anyway in my situation.  I will give you credit for your work, though.  I apologize for taking up your time.
0
 
InteractiveMindCommented:
lol - Okay then.  :-)
0
All Courses

From novice to tech pro — start learning today.