Results 1 to 3 of 3
  1. #1
    sehudson's Avatar
    sehudson is offline Senior Member
    Join Date
    Mar 2010
    Posts
    340
    Rep Power
    5

    Default Problem splitting a string

    I am trying to split up a filename into parts:

    Java Code:
                String filename = file.getName();
                System.out.println("File: "+filename);
                String[] parts = filename.split(".");
                System.out.println(parts[0]);
    My output is:

    File: hello.txt

    Then I get an indexoutOfBounds exception when trying to print out parts[0].

    I even went so far as to iterate over each character in the filename string and keep a count of the "." instances, and it gives me back a 1 so I know it recognizes the period...not sure whats going on.
    Last edited by sehudson; 03-13-2011 at 08:47 PM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by sehudson View Post
    I am trying to split up a filename into parts:

    Java Code:
                String filename = file.getName();
                System.out.println("File: "+filename);
                String[] parts = filename.split(".");
                System.out.println(parts[0]);
    My output is:

    File: hello.txt

    Then I get an indexoutOfBounds exception when trying to print out parts[0].
    split uses a regex and in regex "." has special meaning. You'll want to escape that period:

    Java Code:
    String[] parts = filename.split("\\.");

  3. #3
    sehudson's Avatar
    sehudson is offline Senior Member
    Join Date
    Mar 2010
    Posts
    340
    Rep Power
    5

Similar Threads

  1. Replies: 1
    Last Post: 02-07-2011, 08:22 PM
  2. Replies: 3
    Last Post: 03-03-2010, 12:23 AM
  3. String Splitting
    By A.M.S in forum New To Java
    Replies: 1
    Last Post: 12-04-2009, 07:17 AM
  4. Splitting single string into array elements
    By phil128 in forum New To Java
    Replies: 11
    Last Post: 01-12-2009, 11:51 AM
  5. splitting string and replacing
    By itsme in forum New To Java
    Replies: 1
    Last Post: 12-11-2007, 03:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •