#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    13
    Rep Power
    0

    Split 1 String into 2 seperate strings


    I need help figuring out how to split 1 unknown string Ex: "Firstname Lastname" into two seperate strings String a: "Firstname" String b: "Lastname"
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,021
    Rep Power
    1285
    Look at split() in String
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    13
    Rep Power
    0
    Still stuck with trying to print out the second part of the string (last). All I get is the first name, if anyone can see what's wrong with my code or have any pointers would be great

    import java.util.*;
    public class YourName
    {
    public static void main(String [] args)
    {
    Scanner kb = new Scanner(System.in);
    System. out. println ("What is your Name?");
    String name;
    name = kb.next();
    String [] data = name.split(" ");
    String first;
    String last;
    first = (data[0]);
    last = (data[1]);
    System.out.println(first + last);
    }
    }
  6. #4
  7. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,021
    Rep Power
    1285
    Remember next() will just give you the next token, a String. Have you tried nextLine()?
  8. #5
  9. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    What is the value of last when you execute the code?
    I would expect an ArrayIndexOutOfBoundsException: 1
    error with the posted code.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    13
    Rep Power
    0
    Bullet - thanks for the suggestion, finally works

IMN logo majestic logo threadwatch logo seochat tools logo